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

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

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Toast;

import com.ntels.kneet.v3.R;
import com.ntels.kneet.v3.common.AppConfig;
import com.ntels.kneet.v3.common.Constants;
import com.ntels.kneet.v3.common.c_interface.Main_Interface;
import com.ntels.kneet.v3.common.c_interface.OnDataSendToReslut;
import com.ntels.kneet.v3.common.http.HttpSend;
import com.ntels.kneet.v3.common.http.Response;
import com.ntels.kneet.v3.common.util.Dlog;
import com.ntels.kneet.v3.common.util.LogUtil;
import com.ntels.kneet.v3.common.util.Util;
import com.ntels.kneet.v3.common.websocket.WebSocketService;
import com.ntels.kneet.v3.common.websocket.onWebSocketResponse;
import com.ntels.kneet.v3.common.widget.CustomActivity;
import com.ntels.kneet.v3.view.dialog.CustomDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

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

    private static final String TAG = Things_Homehub_Set_Password.class.getSimpleName();

    /*통신 관련*/
    private              int                                iType                                      = 0;
    private static final int                                MSG_COM_P_HOMEGRP                          = 1;
    private static final int                                MSG_COM_WS_DEVICE_REGISTER                 = 2;

    /*공통*/
    private Activity           act;
    private AppConfig          appConfig;
    private Intent             intent;
    private Util               util                         = new Util();
    private CustomDialog       customDialog                 = new CustomDialog();
    private String             sWS_device_manufacturer      = "";
    private String             sWS_device_model_number      = "";
    private String             sWS_device_serial_number     = "";
    private String             sWS_device_profile_version   = "";
    private String             sPass                        = "";
    private WebSocketService   webSocketService;
    private boolean            bBound                       = false;

    /**
     * <PRE>
     * 1. MethodName: onCreate
     * 2. ClassName :
     * 3. Comment   : onCreate
     * 4. Developer : 정백호
     * 5. Created   : 2016. 07.
     * </PRE>
     */
    @Override public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

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

        Intent serviceIntent = new Intent(act, WebSocketService.class);
        act.bindService(serviceIntent, serviceConnection, Context.BIND_AUTO_CREATE);

        View viewToLoad = LayoutInflater.from(act).inflate(R.layout.things_homehub_set_password, 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();
            sWS_device_manufacturer = intent.getStringExtra(Constants.EXTRA_DEVICE_MANUFACTURER);
            sWS_device_model_number = intent.getStringExtra(Constants.EXTRA_DEVICE_MODEL_NUMBER);
            sWS_device_serial_number = intent.getStringExtra(Constants.EXTRA_DEVICE_SERIAL_NUMBER);
            sWS_device_profile_version = intent.getStringExtra(Constants.EXTRA_DEVICE_PROFILE_VERSION);
        }

        util.getView(act, R.id.llBtn1).setOnClickListener(this);
        util.getView(act, R.id.btnExit).setOnClickListener(this);

        setDisp();
    }

    private void setDisp() {

        //        util.getTextView(act, R.id.edtName).setText(appConfig.getNickname());
    }

    @Override public void onConfigurationChanged(Configuration newConfig) {

        super.onConfigurationChanged(newConfig);
    }

    @Override public void onClick(View v) {

        switch (v.getId()) {
            case R.id.llBtn1:
                sPass = util.getEditTextVal(act, R.id.edtPass);
                String sPassConfirm = util.getEditTextVal(act, R.id.edtPassConfirm);
                if ( sPass.equals("") ) {
                    util.setShowToast(act, util.getString(act, R.string.layout_things_guide_16) + util.getString(act, R.string.MSG901), Toast.LENGTH_SHORT);
                    return;
                }
                if ( sPassConfirm.equals("") ) {
                    util.setShowToast(act, util.getString(act, R.string.layout_things_guide_17) + util.getString(act, R.string.MSG902), Toast.LENGTH_SHORT);
                    return;
                }

                if ( !sPass.equals(sPassConfirm) ) {
                    util.setShowToast(act, util.getString(act, R.string.MSG863), Toast.LENGTH_SHORT);
                    return;
                }

                // 사용자 홈그룹이 없으면 홈그룹 생성 후 디바이스 등록
                if ( appConfig.getSelect_Homegrp_Id().isEmpty() ) {
                    ComHandler.sendMessageDelayed(ComHandler.obtainMessage(MSG_COM_P_HOMEGRP), 10);
                } else {
                    ComHandler.sendMessageDelayed(ComHandler.obtainMessage(MSG_COM_WS_DEVICE_REGISTER), 10);
                }
                break;
            case R.id.btnExit:

                onBackPressed();
                break;
            default:
                break;
        }
    }

    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:
                    send_P_homegrp();
                    break;
                case MSG_COM_WS_DEVICE_REGISTER:
                    if ( bBound ) {
                        send_WS_device_register();
                    } else {
                        LogUtil.i(TAG, "Websocket service is not connected");
                    }
                    break;

                default:
                    break;
            }
            return true;
        }
    }

    /**
     * <PRE>
     * 1. MethodName: send_P_homegrp
     * 2. ClassName :
     * 3. Comment   : [SEND][POST] (홈그룹에 속해 있지 않은 회원이 마스터가 되는) 홈그룹을 새로 생성한다.
     * 4. Developer : 정백호
     * 5. Created   : 2016. 07.
     * </PRE>
     */
    private void send_P_homegrp() {

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

                    result_P_homegrp(result);
                }
            });
            httpSend.P_homegrp();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * <PRE>
     * 1. MethodName: send_P_homegrp
     * 2. ClassName :
     * 3. Comment   : [RESULT] (홈그룹에 속해 있지 않은 회원이 마스터가 되는) 홈그룹을 새로 생성한다.
     * 4. Developer : 정백호
     * 5. Created   : 2016. 07.
     * </PRE>
     */
    private void result_P_homegrp(Response rpResult) {

        try {
            if ( rpResult.getStatusCode() == 200 ) {
                JSONObject joResult = new JSONObject(rpResult.getContent());
                Dlog.v(joResult.toString());

                String sHTTP_homegrp_id = util.null2string(joResult.get(Constants.HTTP_homegrp_id));
                appConfig.setSelect_Homegrp_Id(sHTTP_homegrp_id);

                ComHandler.sendMessageDelayed(ComHandler.obtainMessage(MSG_COM_WS_DEVICE_REGISTER), 10);
            } 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));

                if ( sERR_CODE.equals("401") ) {
                    customDialog.MsgAlert(act, Constants.MSG998, sERR_MSG);
                } else if ( sERR_CODE.equals("401-106") ) {
                    customDialog.MsgAlert(act, Constants.MSG997, sERR_MSG);
                } else {
                    util.setShowToast(act, sERR_MSG, Toast.LENGTH_SHORT);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            customDialog.MsgAlert(act, Constants.MSG807);
        }
    }

    private void result_P_devices_partner_device_ownership(Response rpResult) {

        try {
            if ( rpResult.getStatusCode() == 200 ) {
                JSONObject joResult = new JSONObject(rpResult.getContent());
                Dlog.v(joResult.toString());

                String sHTTP_device_id = util.null2string(joResult.get(Constants.HTTP_device_id));
                appConfig.setSelect_Homegrp_Homehub_Device_Id(sHTTP_device_id);

                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));

                if ( sERR_CODE.equals("401") ) {
                    customDialog.MsgAlert(act, Constants.MSG998, sERR_MSG);
                } else if ( sERR_CODE.equals("401-106") ) {
                    customDialog.MsgAlert(act, Constants.MSG997, sERR_MSG);
                } else {
                    util.setShowToast(act, sERR_MSG, Toast.LENGTH_SHORT);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            customDialog.MsgAlert(act, Constants.MSG807);
        }
    }

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

        customDialog.MsgAlert(act, Constants.MSG905);
        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();
        // }
        // }
    }

    @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.MSG807:
                if ( iBtnResult == 1 ) {
                    ComHandler.sendMessageDelayed(ComHandler.obtainMessage(iType), 10);
                }
                break;
            case Constants.MSG833:
                if ( iBtnResult == 1 ) {
                    onBackPressed();
                }
                break;
            case Constants.MSG905:
                if ( iBtnResult == 1 ) {
                    setResult(RESULT_CANCELED);
                    finish();
                }
                break;
            default:
                break;
        }
    }

    /**
     *  Service bind listener
     *
     */
    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            LogUtil.i(TAG, "");
            WebSocketService.WebSocketBinder binder = (WebSocketService.WebSocketBinder) service;
            webSocketService = binder.getService();
            webSocketService.addWebSocketResponse(webSocketResponse);
            bBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            bBound = false;
        }
    };

    /**
     * <PRE>
     * 1. MethodName: send_WS_device_register
     * 2. ClassName :
     * 3. Comment   : [Send]서비스 허브에 홈허브 디바이스를 등록한다.
     * 4. Developer : 정백호
     * 5. Created   : 2016. 07.
     * </PRE>
     */
    private void send_WS_device_register() {
        HashMap<String, Object> sendParams = new HashMap<>();
        sendParams.put(Constants.WEBSOCKET_KEY_MESSAGE_TYPE, Constants.WEBSOCKET_TYPE_DEVICE_REGISTER);
        sendParams.put(Constants.WEBSOCKET_KEY_DEVICE_MANUFACTURER, sWS_device_manufacturer);
        sendParams.put(Constants.WEBSOCKET_KEY_DEVICE_MODEL_NUMBER, sWS_device_model_number);
        sendParams.put(Constants.WEBSOCKET_KEY_DEVICE_SERIAL_NUMBER, sWS_device_serial_number);
        sendParams.put(Constants.WEBSOCKET_KEY_DEVICE_PROFILE_VERSION, sWS_device_profile_version);
        sendParams.put(Constants.WEBSOCKET_KEY_DEVICE_PASSWORD, sPass);
        sendParams.put(Constants.WEBSOCKET_KEY_REQUEST_ID, appConfig.getiSelect_Servicehub_Request_Id());

        webSocketService.send(Constants.WEBSOCKET_SEND_DEVICE_REGISTER, sendParams);
    }

    /**
     *  WebSocket listener
     *
     */
    private onWebSocketResponse webSocketResponse = new onWebSocketResponse() {
        @Override
        public void onWebSocketResponse(String result) {
            try {
                JSONObject jsonObject = new JSONObject(result);
                LogUtil.i(TAG, "websocket message type : " + jsonObject.get(Constants.WEBSOCKET_KEY_MESSAGE_TYPE));
                String resultCode = util.null2string(jsonObject.get(Constants.WEBSOCKET_KEY_RESULT_CODE));
                String resultMsg = "";
                if ( jsonObject.has(Constants.WEBSOCKET_KEY_RESULT_MSG) ) {
                    resultMsg = util.null2string(jsonObject.get(Constants.WEBSOCKET_KEY_RESULT_MSG));
                }
                if ( resultCode.equals("00") ) {
                    appConfig.setSelect_Homegrp_Id(util.null2string(jsonObject.get(Constants.WEBSOCKET_KEY_HOME_GROUP_ID)));
                    appConfig.setSelect_Homegrp_Homehub_Device_Id(util.null2string(Constants.WEBSOCKET_KEY_DEVICE_ID));
                    appConfig.setsSelect_Homegrp_Homehub_Device_Key(util.null2string(Constants.WEBSOCKET_KEY_DEVICE_KEY));
                    intent = new Intent();
                    act.setResult(RESULT_OK, intent);
                    finish();
                } else {
                    final String finalResultMsg = resultMsg;
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            util.setShowToast(act, finalResultMsg, Toast.LENGTH_SHORT);
                        }
                    });
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onWebSocketError(String message) {

        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if ( bBound ) {
            webSocketService.removeWebSocketResponse(webSocketResponse);
            unbindService(serviceConnection);
            bBound = false;
        }
    }
}
