/*
 * 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.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 :   ThingsDeviceAdd1st
 * 2. FileName  :   ThingsDeviceAdd1st.java
 * 3. Package   :   com.ntels.onecable.view.things
 * 4. Date      :   2016-11-25
 * 5. Author    :   aaron
 * 6. Comment   :   Initialize
 * </pre>
 */
public class ThingsDeviceAdd1st extends CustomActivity implements View.OnClickListener,
        CustomDialog.OnMsgAlterToResult {

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

    /*통신 관련*/
    private int mType = 0;
    private static final int MSG_COM_WS_NODE_COMMAND = 1;

    /*공통*/
    private Activity mActivity;
    private AppConfig mAppConfig;
    private Intent mIntent;
    private Util mUtil = new Util();
    private CustomDialog mCustomDialog = new CustomDialog();
    private String mDeviceName = "";
    private String mCompanyName = "";
    private String mDeviceDesc = "";
    private String mDeviceDesc1 = "";
    private int mDeviceImageId = 0;
    private int mDeviceImageId1 = 0;
    private WebSocketService mWebSocketService;
    private boolean mIsBound = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        mActivity = ThingsDeviceAdd1st.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_device_add_01,
                null);
        this.setContentView(viewToLoad);

        Intent intent = getIntent();
        mDeviceName = intent.getStringExtra(Constants.EXTRA_DEVICE_NAME);
        mCompanyName = intent.getStringExtra(Constants.EXTRA_COMPANY_NAME);
        mDeviceDesc = intent.getStringExtra(Constants.EXTRA_DEVICE_DESC);
        mDeviceDesc1 = intent.getStringExtra(Constants.EXTRA_DEVICE_DESC1);
        mDeviceImageId = intent.getIntExtra(Constants.EXTRA_DEVICE_IMAGE, 0);
        mDeviceImageId1 = intent.getIntExtra(Constants.EXTRA_DEVICE_IMAGE1, 0);

        setDisp();
    }

    @Override
    public void onClick(View view) {
        LogUtil.i(TAG, "onClick!!");
        switch (view.getId()) {
            case R.id.llBtn2:
                onBackPressed();
                break;
            case R.id.llBtn1:
                LogUtil.i(TAG, "onClick : start!!");
                if (mAppConfig.getSelect_Homegrp_Homehub_Online_State().equals("ON")) {
                    LogUtil.i(TAG, "mCompanyName : " + mCompanyName);
                    if (mCompanyName.equals(getString(R.string.layout_things_device_add_17))) {
                        mIntent = new Intent(mActivity, ThingsDeviceNetatmoLogin.class);
                        mUtil.callActivityForResultNoAnim(mActivity, mIntent,
                                Constants.ACT_THINGS_DEVICE_NETATMO_LOGIN);
                    } else {
                        mUtil.getView(mActivity, R.id.llBtn1).setEnabled(false);
                        mUtil.getView(mActivity, R.id.btnReStart).setEnabled(false);
                        comHandler.sendMessageDelayed(comHandler.obtainMessage(
                                MSG_COM_WS_NODE_COMMAND), Constants.HANDLER_DELAY_MILLIS);
                    }
                } else {
                    mUtil.setShowToast(mActivity, mUtil.getString(mActivity, R.string.MSG866),
                            Toast.LENGTH_SHORT);
                    return;
                }
                break;
            case R.id.btnReStart:
                if (mAppConfig.getSelect_Homegrp_Homehub_Online_State().equals("ON")) {
                    mUtil.getView(mActivity, R.id.llBtn1).setEnabled(false);
                    mUtil.getView(mActivity, R.id.btnReStart).setEnabled(false);
                    comHandler.sendMessageDelayed(comHandler.obtainMessage(
                            MSG_COM_WS_NODE_COMMAND), Constants.HANDLER_DELAY_MILLIS);
                } else {
                    mUtil.setShowToast(mActivity, mUtil.getString(mActivity, R.string.MSG866),
                            Toast.LENGTH_SHORT);
                    return;
                }
                break;
            default:
                break;
        }
    }

    @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;
            default:
                break;
        }
    }

    @Override
    public void onBackPressed() {

        mIntent = new Intent();
        mActivity.setResult(RESULT_CANCELED, mIntent);
        finish();
        return;
    }

    @Override
    public void onResume() {

        super.onResume();

        if (mIsBound) {
            if (webSocketResponse != null) {
                mWebSocketService.addWebSocketResponse(webSocketResponse);
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == mActivity.RESULT_OK) {
            switch (requestCode) {
                case Constants.ACT_THINGS_DEVICE_ADD_02:
                    setResult(RESULT_OK, data);
                    finish();
                    break;
                case Constants.ACT_THINGS_DEVICE_NETATMO_LOGIN:
                    setResult(RESULT_OK, data);
                    finish();
                    break;
                default:
                    break;
            }
        } else {
            switch (requestCode) {
                case Constants.ACT_THINGS_DEVICE_ADD_02:
                    Boolean isFlowEnd = data.getBooleanExtra(Constants.EXTRA_FLOW_END_FLAG, false);
                    Boolean isTimeout = data.getBooleanExtra(Constants.EXTRA_TIMEOUT_FLAG, false);
                    if (isFlowEnd) {
                        mActivity.setResult(RESULT_CANCELED, data);
                        finish();
                    } else {
                        mUtil.getView(mActivity, R.id.llPageRoot).setVisibility(View.VISIBLE);
                        if (isTimeout) {
                            mUtil.getView(mActivity, R.id.llBtn1).setVisibility(View.GONE);
                            mUtil.getView(mActivity, R.id.llStart).setVisibility(View.GONE);
                            mUtil.getView(mActivity, R.id.llReStart).setVisibility(View.VISIBLE);
                        } else {
                            mUtil.getView(mActivity, R.id.llBtn1).setVisibility(View.VISIBLE);
                            mUtil.getView(mActivity, R.id.llStart).setVisibility(View.VISIBLE);
                            mUtil.getView(mActivity, R.id.llReStart).setVisibility(View.GONE);
                        }
                    }
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    protected void onDestroy() {

        super.onDestroy();

        if (mIsBound) {
            mWebSocketService.removeWebSocketResponse(webSocketResponse);
            unbindService(serviceConnection);
            mIsBound = false;
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mIsBound) {
            mWebSocketService.removeWebSocketResponse(webSocketResponse);
        }
    }

    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_WS_NODE_COMMAND:
                    sendWsDeviceCommand();
                    break;

                default:
                    break;
            }
            return true;
        }
    }

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

    private OnWebSocketResponse webSocketResponse = new OnWebSocketResponse() {
        @Override
        public void onResponse(String result) {
            try {

                JSONObject jsonObject = new JSONObject(result);
                String messageType =
                        mUtil.null2string(jsonObject.get(Constants.KEY_MESSAGE_TYPE));
                LogUtil.i(TAG, "websocket message mType : " + messageType);

                if (messageType.equals(Constants.WEBSOCKET_TYPE_DEVICE_COMMAND_RESULT)) {
                    notificationWsDeviceCommandResult(jsonObject);
                } else if (messageType.equals(Constants.WEBSOCKET_TYPE_DEVICE_COMMAND)) {
                    resultWsDeviceCommandResult(jsonObject);
                } else {
                    // TODO: 2016-11-25 : 처리 정책?
                }
            } catch (JSONException ex) {
                ex.printStackTrace();
            }
        }

        @Override
        public void onError(int code, String message) {
            mCustomDialog.msgAlert(mActivity, Constants.MSG807);
        }
    };

    /**
     * UI display.
     */
    private void setDisp() {

        mUtil.getView(mActivity, R.id.llPageRoot).setVisibility(View.VISIBLE);

        mUtil.getView(mActivity, R.id.llStart).setVisibility(View.VISIBLE);
        mUtil.getView(mActivity, R.id.llReStart).setVisibility(View.GONE);
        mUtil.getView(mActivity, R.id.llBtn1).setOnClickListener(this);
        mUtil.getView(mActivity, R.id.llBtn2).setOnClickListener(this);
        mUtil.getView(mActivity, R.id.btnReStart).setOnClickListener(this);

        mUtil.getTextView(mActivity, R.id.tvDeviceName).setText(mDeviceName);
        mUtil.getTextView(mActivity, R.id.tvCompanyName).setText(mCompanyName);
        mUtil.getTextView(mActivity, R.id.tvDeviceDesc).setText(mDeviceDesc);
        mUtil.setImage(mActivity, mDeviceImageId, R.id.ivIconDevice);
    }

    /**
     * 서비스 허브에 디바이스제어(노드 페어링 모드)를 요청한다.
     */
    private void sendWsDeviceCommand() {
        HashMap<String, Object> sendParams = new HashMap<>();
        sendParams.put(Constants.KEY_MESSAGE_TYPE,
                Constants.WEBSOCKET_TYPE_DEVICE_COMMAND);
        sendParams.put(Constants.KEY_DEVICE_ID,
                mAppConfig.getSelect_Homegrp_Homehub_Device_Id());
        sendParams.put(Constants.KEY_COMMAND_TYPE,
                Constants.WEBSOCKET_COMM_TYPE_PAIRING_START);
        sendParams.put(Constants.KEY_REQUEST_ID,
                mAppConfig.getiSelect_Servicehub_Request_Id());

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

    /**
     * 디바이스 제어(노드 페어링 모드)를 요청 결과.
     *
     * @param jsonResult 결과 json object
     */
    private void resultWsDeviceCommandResult(JSONObject jsonResult) {
        try {
            if (!jsonResult.get(Constants.KEY_RESULT_CODE).equals("00")) {
                LogUtil.i(TAG, jsonResult.getString(Constants.KEY_RESULT_MSG));
                mCustomDialog.msgAlert(mActivity, Constants.MSG836);
                mUtil.getView(mActivity, R.id.llBtn1).setEnabled(true);
                mUtil.getView(mActivity, R.id.btnReStart).setEnabled(true);
            }
        } catch (JSONException ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 서비스 허브에 디바이스 제어(노드 페어링 모드) 결과를 푸쉬 받는다.
     *
     * @param jsonResult 결과 json object
     * @throws JSONException json parsing exception
     */
    private void notificationWsDeviceCommandResult(JSONObject jsonResult) throws JSONException {
        try {
            if (jsonResult.get(Constants.KEY_COMMAND_STATUS).equals("SUCCESS")) {

                mUtil.getView(mActivity, R.id.llPageRoot).setVisibility(View.INVISIBLE);
                mIntent = new Intent(mActivity, ThingsDeviceAdd2nd.class);
                mIntent.putExtra(Constants.EXTRA_DEVICE_NAME, mDeviceName);
                mIntent.putExtra(Constants.EXTRA_COMPANY_NAME, mCompanyName);
                mIntent.putExtra(Constants.EXTRA_DEVICE_DESC1, mDeviceDesc1);
                mIntent.putExtra(Constants.EXTRA_DEVICE_IMAGE1, mDeviceImageId1);
                String commandId = mUtil.null2string(jsonResult.get(Constants.KEY_COMMAND_ID));
                mIntent.putExtra(Constants.EXTRA_COMMAND_ID, commandId);
                mIntent.putExtra(Constants.EXTRA_DEVICE_ID,
                        mAppConfig.getSelect_Homegrp_Homehub_Device_Id());
                mUtil.callActivityForResultNoAnim(mActivity, mIntent,
                        Constants.ACT_THINGS_DEVICE_ADD_02);
            } else {
                Dlog.v(jsonResult.toString());
                if (jsonResult.has(Constants.KEY_COMMAND_MESSAGE)) {
                    String errorMsg = mUtil.null2string(
                            jsonResult.get(Constants.KEY_COMMAND_MESSAGE));
                    mCustomDialog.msgAlert(mActivity, Constants.MSG000, errorMsg);
                } else {
                    mCustomDialog.msgAlert(mActivity, Constants.MSG807);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            mCustomDialog.msgAlert(mActivity, Constants.MSG807);
        } finally {
            mUtil.getView(mActivity, R.id.llBtn1).setEnabled(true);
            mUtil.getView(mActivity, R.id.btnReStart).setEnabled(true);
        }
    }

}

