/*
 * Copyright (c) 2015. Ncomz. All Rights Reserved
 */

package com.ntels.kneet.v3.view.invitation;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;

import com.ntels.kneet.v3.common.AppConfig;
import com.ntels.kneet.v3.common.Constants;
import com.ntels.kneet.v3.common.db.SQLManager;
import com.ntels.kneet.v3.common.http.HttpSend;
import com.ntels.kneet.v3.common.http.Response;
import com.ntels.kneet.v3.common.c_interface.OnDataSendToReslut;
import com.ntels.kneet.v3.common.util.Dlog;
import com.ntels.kneet.v3.common.util.Util;
import com.ntels.kneet.v3.common.widget.CustomActivity;
import com.ntels.kneet.v3.R;
import com.ntels.kneet.v3.view.dialog.CustomDialog;
import com.ntels.kneet.v3.view.dialog.Dialog_Date;

import org.json.JSONObject;

import java.util.ArrayList;

public class Invitation_Reply extends CustomActivity implements View.OnClickListener,
                                                                CustomDialog.OnMsgAlterToResult {

    /** Called when the activity is first created. */

    private SQLManager sqlManager = new SQLManager();
    private Activity act;
    Intent intent;
    Button btnCheck[];
    private AppConfig appConfig;
    private Util         util         = new Util();
    private CustomDialog customDialog = new CustomDialog();
    ArrayList<String> aList1 = new ArrayList<String>();
    ArrayList<String> aList2 = new ArrayList<String>();
    private              int               iPosition                             = 0;
    private              int               iType                                 = 0;
    private static final int               MSG_COM_P_HOMEGRP_MEMBERS_INVITATIONS = 1;
    private              String            sHTTP_homegrp_id                      = "";
    private              String            sHTTP_status_code                     = "Y";
    //    private              String            sHTTP_target_email               = "";
    private              String            sHTTP_image_file_name                 = "";
    private              String            sHTTP_authorization_question          = "";
    private              String            sHTTP_authorization_reply             = "";
    private              String            sHTTP_error_count                     = "";
    private static final int               MSG_COM_WEATHER_LOCATION_CODES        = 1;
    private              int               iAreaPosition                         = -1;
    private              String            sArea                                 = "";
    private              ArrayList<String> alAreaTitle                           = new ArrayList<String>();
    private              ArrayList<String> alAreaId                              = new ArrayList<String>();

    private boolean bReloadFinishFlag = false;

    /**
     * <PRE>
     * 1. MethodName: onCreate
     * 2. ClassName :
     * 3. Comment   : onCreate
     * 4. Developer : 최진오
     * 5. Created   : 2015. 10.
     * </PRE>
     */
    @Override public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        act = Invitation_Reply.this;
        appConfig = (AppConfig) act.getApplicationContext();
        customDialog.setOnMsgAlterToResultEvent(this);

        View viewToLoad = LayoutInflater.from(act).inflate(R.layout.invitation_reply, null);
        this.setContentView(viewToLoad);

        if ( savedInstanceState != null ) {
            // sTitle =
            // savedInstanceState.getString(Constants.EXTRA_SPINNER_TITLE);
            // aList1 =
            // savedInstanceState.getStringArrayList(Constants.EXTRA_SPINNER_LIST1);
            // aList2 =
            // savedInstanceState.getStringArrayList(Constants.EXTRA_SPINNER_LIST2);
            // // 0: 세로 한개 선택, 1: 가로 한개선택
            // iType = savedInstanceState.getInt(Constants.EXTRA_SPINNER_TYPE,
            // 0);
            // sBtn1 =
            // savedInstanceState.getString(Constants.EXTRA_SPINNER_BTN1);
            // sBtn2 =
            // savedInstanceState.getString(Constants.EXTRA_SPINNER_BTN2);
            // iPosition =
            // savedInstanceState.getInt(Constants.EXTRA_SPINNER_POSITION, 0);
        } else {
            Intent intent = getIntent();
            sHTTP_homegrp_id = util.null2string(intent.getStringExtra(Constants.HTTP_homegrp_id));
            //            sHTTP_target_email = util.null2string(intent.getStringExtra(Constants.HTTP_target_email));
            sHTTP_authorization_question = util.null2string(intent.getStringExtra(Constants.HTTP_authorization_question));
            sHTTP_image_file_name = util.null2string(intent.getStringExtra(Constants.HTTP_image_file_name));
        }

        displayListView();
    }

    private void displayListView() {

        util.getView(act, R.id.btnDate).setOnClickListener(this);
        util.getView(act, R.id.llBtn1).setOnClickListener(this);
        util.getTextView(act, R.id.tvTitle).setText(sHTTP_authorization_question);
        util.setRefreshImage(act, sHTTP_image_file_name, R.id.ivMemberIcon);
    }

    @Override public void onClick(View v) {

        switch (v.getId()) {
            case R.id.llBtn1:
                onBackPressed();
                break;
            case R.id.btnDate:
                v.setEnabled(false);
                Dialog_Date dp1 = new Dialog_Date(act);
                dp1.setTitle(util.getString(act, R.string.layout_invitation_reply_02));
                dp1.setBtn1Val(util.getString(act, R.string.layout_ok));
                dp1.setBtn2Val(util.getString(act, R.string.layout_cancel));
                dp1.setMinDateVal("1900-01-01");
                dp1.setMaxDateVal("2100-12-31");
                dp1.setDtpVal(new Dialog_Date.DatePickerListner() {
                    @Override public void OnDoneButton(Dialog datedialog, String sDateVal) {

                        sHTTP_authorization_reply = sDateVal;
                        datedialog.dismiss();
                        ComHandler.sendMessageDelayed(ComHandler.obtainMessage(
                                MSG_COM_P_HOMEGRP_MEMBERS_INVITATIONS), 10);
                    }

                    @Override public void OnCancelButton(Dialog datedialog) {

                        datedialog.dismiss();
                        try {
                            util.getView(act, R.id.btnDate).setEnabled(true);
                        } catch (Exception ex) {

                        }
                    }
                });
                dp1.init();
                dp1.show();
            default:
                break;
        }
    }

    @Override public void onConfigurationChanged(Configuration newConfig) {

        super.onConfigurationChanged(newConfig);
    }

    /**
     * <PRE>
     * 1. MethodName: onBackPressed
     * 2. ClassName :
     * 3. Comment   : onBackPressed
     * 4. Developer : 최진오
     * 5. Created   : 2015. 10.
     * </PRE>
     */
    @Override public void onBackPressed() {

        intent = new Intent();
        intent.putExtra(Constants.EXTRA_RELOAD_FLAG, bReloadFinishFlag);
        act.setResult(RESULT_CANCELED, intent);
        finish();
        return;
    }

    /**
     * <PRE>
     * 1. MethodName: onResume
     * 2. ClassName :
     * 3. Comment   : onResume
     * 4. Developer : 최진오
     * 5. Created   : 2015. 10.
     * </PRE>
     */
    @Override public void onResume() {

        super.onResume();

        // if (!GreenBilllab.getIntro()) {
        // if (Main.reLoginCheck()) {
        // onBackPressed();
        // }
        // }
    }

    Handler ComHandler = new Handler(new IncomingHandlerCallBack());

    class IncomingHandlerCallBack implements Handler.Callback {

        @Override public boolean handleMessage(Message msg) {

            iType = msg.what;
            switch (msg.what) {
                case MSG_COM_P_HOMEGRP_MEMBERS_INVITATIONS:
                    send_P_homegrp_members_invitations();
                    break;
                default:
                    break;
            }
            return true;
        }
    }

    private void send_P_homegrp_members_invitations() {

        try {
            HttpSend httpSend;
            httpSend = new HttpSend(act);
            httpSend.setOnDataSendToReslutEvent(new OnDataSendToReslut() {
                @Override public void resultResponse(Response result) {

                    result_P_homegrp_members_invitations(result);
                }
            });
            httpSend.P_homegrp_members_invitations(sHTTP_homegrp_id, sHTTP_status_code, sHTTP_authorization_reply);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private void result_P_homegrp_members_invitations(Response rpResult) {

        try {
            if ( rpResult.getStatusCode() == 200 ) {
                JSONObject joResult = new JSONObject(rpResult.getContent());
                Dlog.v(joResult.toString());
                String sHTTP_homegrp_id = "";
                if ( joResult.has(Constants.HTTP_homegrp_id) ) {
                    sHTTP_homegrp_id = util.null2string(joResult.get(Constants.HTTP_homegrp_id));
                }

                String sHTTP_homegrp_image_file_name = "";
                if ( joResult.has(Constants.HTTP_homegrp_image_file_name) ) {
                    sHTTP_homegrp_image_file_name = util.null2string(joResult.get(Constants.HTTP_homegrp_image_file_name));
                }

                String sHTTP_homegrp_name = "";
                if ( joResult.has(Constants.HTTP_homegrp_name) ) {
                    sHTTP_homegrp_name = util.null2string(joResult.get(Constants.HTTP_homegrp_name));
                }

                String sHTTP_grade_code = "";
                if ( joResult.has(Constants.HTTP_grade_code) ) {
                    sHTTP_grade_code = util.null2string(joResult.get(Constants.HTTP_grade_code));
                }

//                String sHTTP_homehub_device_id = "";
//                if ( joResult.has(Constants.HTTP_homehub_device_id) ) {
//                    sHTTP_homehub_device_id = util.null2string(joResult.get(Constants.HTTP_homehub_device_id));
//                }
//
//                String sHTTP_homehub_online_state = "";
//                if ( joResult.has(Constants.HTTP_homehub_online_state) ) {
//                    sHTTP_homehub_online_state = util.null2string(joResult.get(Constants.HTTP_homehub_online_state));
//                }
                appConfig.setSelect_Homegrp_Id(sHTTP_homegrp_id);
                appConfig.setSelect_Homegrp_Icon(sHTTP_homegrp_image_file_name);
                appConfig.setSelect_Homegrp_Name(sHTTP_homegrp_name);
                appConfig.setSelect_Homegrp_Grade_Code(sHTTP_grade_code);
//                appConfig.setSelect_Homegrp_Homehub_Device_Id(sHTTP_homehub_device_id);
//                appConfig.setSelect_Homegrp_Homehub_Online_State(sHTTP_homehub_online_state);

                sHTTP_error_count = "";
                bReloadFinishFlag = true;
                intent = new Intent();
                act.setResult(RESULT_OK, intent);
                finish();
            } else {
                JSONObject joResult = new JSONObject(rpResult.getContent());
                Dlog.v(joResult.toString());
                String sERR_CODE = util.null2string(joResult.get(Constants.HTTP_err_code));
                String sERR_MSG = util.null2string(joResult.get(Constants.HTTP_err_msg));
                String sERR_COUNT = util.null2string(joResult.get(Constants.HTTP_error_count));

                if ( sERR_CODE.equals("401") ) {
                    customDialog.MsgAlert(act, Constants.MSG998, sERR_MSG);
                } else if ( sERR_CODE.equals("400-102") ) {
                    sHTTP_error_count = sERR_COUNT;
                    customDialog.MsgAlert(act, Constants.MSG999, sERR_MSG);
                } else if ( sERR_CODE.equals("401-106") ) {
                    customDialog.MsgAlert(act, Constants.MSG997, sERR_MSG);
                } else {
                    customDialog.MsgAlert(act, Constants.MSG000, sERR_MSG);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            customDialog.MsgAlert(act, Constants.MSG807);
        }
        try {
            util.getView(act, R.id.btnDate).setEnabled(true);
        } catch (Exception ex) {

        }
    }

    @Override public void resultCustomDialogResponse(int iMsgID, int iBtnResult) {

        switch (iMsgID) {
            case Constants.MSG998:
                util.callApp_Start(act, "LOGOUT");
                break;
            case Constants.MSG997:
                util.callApp_Start(act, "HOME_RELOAD");
                break;
            case Constants.MSG999:
                if ( iBtnResult == 1 ) {
                    if ( util.str2int(sHTTP_error_count) < 3 ) {
                        util.getView(act, R.id.btnDate).performClick();
                    } else {
                        bReloadFinishFlag = true;
                        onBackPressed();
                    }
                }
                break;
            case Constants.MSG807:
                if ( iBtnResult == 1 ) {
                    ComHandler.sendMessageDelayed(ComHandler.obtainMessage(iType), 10);
                }
                break;
            default:
                break;
        }
    }
}
