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

package com.ntels.onecable.view.things;

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

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

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

import java.util.HashMap;

/**
 * <pre>
 * 1. ClassName :   ThingsHomehubSetPassword
 * 2. FileName  :   ThingsHomehubSetPassword.java
 * 3. Package   :   com.ntels.onecable.view.things
 * 4. Date      :   2016-11-24
 * 5. Author    :   aaron
 * 6. Comment   :   Initialize
 * </pre>
 */
public class ThingsHomehubSetPassword extends CustomActivity implements View.OnClickListener,
        CustomDialog.OnMsgAlterToResult {

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

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

    /*공통*/
    private Activity mActivity;
    private AppConfig mAppConfig;
    private Intent mIntent;
    private Util mUtil = new Util();
    private CustomDialog mCustomDialog = new CustomDialog();
    private String mDeviceManufacturer = "";
    private String mDeviceModelNumber = "";
    private String mDeviceSerialNumber = "";
    private String mDeviceProfileVersion = "";
    private String mMdnsHostAddress = "";
    private String mPass = "";
    private WebSocketService mWebSocketService;
    private boolean mIsBound = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        mActivity = ThingsHomehubSetPassword.this;
        mAppConfig = (AppConfig) mActivity.getApplicationContext();
        mCustomDialog.setOnMsgAlterToResultEvent(this);

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

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

        if (getIntent() != null) {
            Intent intent = getIntent();
            mDeviceManufacturer = intent.getStringExtra(Constants.EXTRA_DEVICE_MANUFACTURER);
            mDeviceModelNumber = intent.getStringExtra(Constants.EXTRA_DEVICE_MODEL_NUMBER);
            mDeviceSerialNumber = intent.getStringExtra(Constants.EXTRA_DEVICE_SERIAL_NUMBER);
            mDeviceProfileVersion = intent.getStringExtra(Constants.EXTRA_DEVICE_PROFILE_VERSION);
            mMdnsHostAddress = intent.getStringExtra(Constants.EXTRA_MDNS_HOST_ADDRESS);
        }

        mUtil.getView(mActivity, R.id.llBtn1).setOnClickListener(this);
        mUtil.getView(mActivity, R.id.btnExit).setOnClickListener(this);
    }

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

    @Override
    public void onClick(View view) {
        LogUtil.i(TAG, "onClick!!");
        switch (view.getId()) {
            case R.id.llBtn1:
                mPass = mUtil.getEditTextVal(mActivity, R.id.edtPass);
                String passConfirm = mUtil.getEditTextVal(mActivity, R.id.edtPassConfirm);
                if ("".equals(mPass)) {
                    mUtil.setShowToast(mActivity,
                            mUtil.getString(mActivity, R.string.layout_things_guide_16)
                                    + mUtil.getString(mActivity, R.string.MSG901), Toast.LENGTH_SHORT);
                    return;
                }
                if ("".equals(passConfirm)) {
                    mUtil.setShowToast(mActivity,
                            mUtil.getString(mActivity, R.string.layout_things_guide_17)
                                    + mUtil.getString(mActivity, R.string.MSG902), Toast.LENGTH_SHORT);
                    return;
                }

                if (!mPass.equals(passConfirm)) {
                    mUtil.setShowToast(mActivity, mUtil.getString(mActivity, R.string.MSG863),
                            Toast.LENGTH_SHORT);
                    return;
                }

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

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

    @Override
    public void onBackPressed() {

        mCustomDialog.msgAlert(mActivity, Constants.MSG905);
        return;
    }

    @Override
    public void resultCustomDialogResponse(int msgId, int btnResult) {

        switch (msgId) {

            case Constants.MSG998:
                mUtil.callApp_Start(mActivity, "LOGOUT");
                break;
            case Constants.MSG997:
                mUtil.callApp_Start(mActivity, "HOME_RELOAD");
                break;
            case Constants.MSG807:
                if (btnResult == 1) {
                    comHandler.sendMessageDelayed(comHandler.obtainMessage(mType),
                            Constants.HANDLER_DELAY_MILLIS);
                }
                break;
            case Constants.MSG833:
                if (btnResult == 1) {
                    onBackPressed();
                }
                break;
            case Constants.MSG905:
                if (btnResult == 1) {
                    setResult(RESULT_CANCELED);
                    finish();
                }
                break;
            default:
                break;
        }
    }

    /**
     * (홈그룹에 속해 있지 않은 회원이 마스터가 되는) 홈그룹을 생성 요청한다.
     */
    private void sendPostHomegrp() {

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

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

    /**
     * 홈그룹 생성 요청 결과.
     *
     * @param result 결과 data
     */
    private void resultPostHomgrp(Response result) {

        try {
            if (result.getStatusCode() == Response.OK) {
                JSONObject joResult = new JSONObject(result.getContent());
                Dlog.v(joResult.toString());

                String resultHomegrpId = mUtil.null2string(joResult.get(Constants.KEY_HOMEGRP_ID));
                mAppConfig.setCtrtGroupId(resultHomegrpId);

                mWebSocketService.webSocketConnect();
            } else {
                JSONObject joResult = new JSONObject(result.getContent());
                Dlog.v(joResult.toString());
                String errorCode = mUtil.null2string(joResult.get(Constants.KEY_ERR_CODE));
                String errorMsg = mUtil.null2string(joResult.get(Constants.KEY_ERR_MSG));

                if ("401".equals(errorCode)) {
                    mCustomDialog.msgAlert(mActivity, Constants.MSG998, errorMsg);
                } else if ("401-106".equals(errorCode)) {
                    mCustomDialog.msgAlert(mActivity, Constants.MSG997, errorMsg);
                } else {
                    mUtil.setShowToast(mActivity, errorMsg, Toast.LENGTH_SHORT);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            mCustomDialog.msgAlert(mActivity, Constants.MSG807);
        }
    }

    /**
     * 등록하려는 홈허브에 device_id, device_key 정보를 전달한다.
     */
    private void sendPostDeviceInfo() {

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

                    resultPostDeviceInfo(result);
                }
            });
            httpSend.P_deviceinfo(mMdnsHostAddress,
                    mAppConfig.getSelect_Homegrp_Homehub_Device_Id(),
                    mAppConfig.getsSelect_Homegrp_Homehub_Device_Key());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 등록하려는 홈허브에 device_id, device_key 정보 전달 결과.
     *
     * @param response 결과 data
     */
    private void resultPostDeviceInfo(Response response) {

        try {
            if (response.getStatusCode() == Response.OK) {
                JSONObject joResult = new JSONObject(response.getContent());
                Dlog.v(joResult.toString());

                String result = mUtil.null2string(joResult.get(Constants.KEY_RESULT));
                if ("SUCCESS".equalsIgnoreCase(result)) {
                    mIntent = new Intent();
                    mActivity.setResult(RESULT_OK, mIntent);
                    finish();
                }
            } else {
                JSONObject joResult = new JSONObject(response.getContent());
                Dlog.v(joResult.toString());
                // TODO : 에러 메세지 정의
                mUtil.setShowToast(mActivity, "홈허브를 재시작해주세요.", Toast.LENGTH_SHORT);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            mCustomDialog.msgAlert(mActivity, Constants.MSG807);
        }
    }

    /**
     * 서비스허브에 홈허브 디바이스를 등록 요청한다.
     */
    private void sendWsDeviceRegister() {
        HashMap<String, Object> sendParams = new HashMap<>();
        sendParams.put(Constants.KEY_MESSAGE_TYPE,
                Constants.WEBSOCKET_TYPE_DEVICE_REGISTER);
        sendParams.put(Constants.KEY_DEVICE_MANUFACTURER, mDeviceManufacturer);
        sendParams.put(Constants.KEY_DEVICE_MODEL_NUMBER, mDeviceModelNumber);
        sendParams.put(Constants.KEY_DEVICE_SERIAL_NUMBER, mDeviceSerialNumber);
        sendParams.put(Constants.KEY_DEVICE_PROFILE_VERSION, mDeviceProfileVersion);
        sendParams.put(Constants.KEY_DEVICE_PASSWORD, mPass);
        sendParams.put(Constants.KEY_REQUEST_ID,
                mAppConfig.getiSelect_Servicehub_Request_Id());

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

    /**
     * 서비스허브에 홈허브 디바이스 등록 요청 결과.
     *
     * @param joResult 결과 data
     * @throws JSONException json parsing exception
     */
    private void resultWsDeviceRegister(JSONObject joResult) throws JSONException {
        String resultCode = mUtil.null2string(joResult.get(Constants.KEY_RESULT_CODE));
        String resultMsg = "";
        if (joResult.has(Constants.KEY_RESULT_MSG)) {
            resultMsg = mUtil.null2string(joResult.get(Constants.KEY_RESULT_MSG));
        }
        if ("00".equals(resultCode)) {
            mAppConfig.setSelect_Homegrp_Homehub_Device_Id(
                    mUtil.null2string(joResult.get(Constants.KEY_DEVICE_ID)));
            mAppConfig.setsSelect_Homegrp_Homehub_Device_Key(
                    mUtil.null2string(joResult.get(Constants.KEY_DEVICE_KEY)));
            comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_P_DEVICEINFO),
                    Constants.HANDLER_DELAY_MILLIS);
        } else {
            final String finalResultMsg = resultMsg;
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mUtil.setShowToast(mActivity, finalResultMsg, Toast.LENGTH_SHORT);
                }
            });
        }
    }

    /**
     * WebSocket listener.
     */
    private OnWebSocketResponse webSocketResponse = new OnWebSocketResponse() {
        @Override
        public void onResponse(String result) {
            try {
                JSONObject jsonObject = new JSONObject(result);
                String msgType = jsonObject.getString(Constants.KEY_MESSAGE_TYPE);
                LogUtil.i(TAG, "websocket message mType : " + msgType);
                if (msgType.equals(Constants.WEBSOCKET_TYPE_DEVICE_REGISTER)) {
                    resultWsDeviceRegister(jsonObject);
                } else if (msgType.equals(Constants.WEBSOCKET_TYPE_AUTH)) {
                    comHandler.sendMessageDelayed(
                            comHandler.obtainMessage(MSG_COM_WS_DEVICE_REGISTER),
                            Constants.HANDLER_DELAY_MILLIS);
                }
            } catch (JSONException ex) {
                ex.printStackTrace();
            }
        }

        @Override
        public void onError(int code, String message) {

        }
    };

    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            LogUtil.i(TAG, "onServiceConnected!!");
            WebSocketService.WebSocketBinder binder = (WebSocketService.WebSocketBinder) service;
            mWebSocketService = binder.getService();
            mWebSocketService.addWebSocketResponse(webSocketResponse);
            mIsBound = true;
        }

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

    Handler comHandler = new Handler(new IncomingHandlerCallBack());

    /**
     * 서버 요청 핸들러.
     */
    class IncomingHandlerCallBack implements Handler.Callback {

        @Override
        public boolean handleMessage(Message msg) {

            mType = msg.what;
            switch (msg.what) {
                case MSG_COM_P_HOMEGRP:
                    sendPostHomegrp();
                    break;
                case MSG_COM_WS_DEVICE_REGISTER:
                    if (mIsBound) {
                        sendWsDeviceRegister();
                    } else {
                        LogUtil.i(TAG, "Websocket service is not connected");
                    }
                    break;
                case MSG_COM_P_DEVICEINFO:
                    sendPostDeviceInfo();
                    break;

                default:
                    break;
            }
            return true;
        }
    }

}
