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

package com.ntels.onecable.admin.view.things;

import com.ntels.onecable.admin.R;
import com.ntels.onecable.admin.common.AppConfig;
import com.ntels.onecable.admin.common.Constants;
import com.ntels.onecable.admin.common.util.Dlog;
import com.ntels.onecable.admin.common.util.LogUtil;
import com.ntels.onecable.admin.common.util.Util;
import com.ntels.onecable.admin.common.websocket.WebSocketService;
import com.ntels.onecable.admin.common.widget.CustomActivity;
import com.ntels.onecable.admin.view.dialog.CustomDialog;

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

import android.app.Activity;
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.ProgressBar;

import java.util.HashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

import static com.ntels.onecable.admin.common.Constants.EXTRA_ERROR_CODE;
import static com.ntels.onecable.admin.common.Constants.EXTRA_RESULT_STATE;

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

    private static final String TAG = ThingsDeviceAddStep3.class.getSimpleName();
    private static final int MSG_COM_WS_DEVICE_COMMAND_PAIRING_START = 1;
    private static final int MSG_COM_WS_DEVICE_COMMAND_PAIRING_STOP = 2;
    private static final int CONNECT_MAX_TIME_SEC = 60;
    Handler comHandler = new Handler(new IncomingHandlerCallBack());
    ProgressBar mProgressBar;
    /*통신 관련*/
    private int mType = 0;
    /*공통*/
    private Activity mActivity;
    private AppConfig mAppConfig;
    private Intent mIntent;
    private Util mUtil = new Util();
    private CustomDialog mCustomDialog = new CustomDialog();
    private String mStartCommandId = "";
    private String mStopCommandId = "";
    private String mDeviceName = "";
    private String mCompanyName = "";
    private String mDeviceDelDesc = "";
    private String mDeviceAddDesc = "";
    private int mDeviceImageId = 0;
    private int mDeviceImageId1 = 0;
    private String mDeviceId = "";
    private String mNodeId = "";
    //    private WebSocketService mWebSocketService;
    private boolean mIsBound = false;
    private ScheduledFuture mScheduledFuture;
    private Boolean mIsEnd = false;
    private Boolean mIsPollingPause = false;
    private Boolean mIsPollingCancel = false;
    private int mMaxTime = CONNECT_MAX_TIME_SEC;
    private int mTotal = 0;
    Runnable runnable = new Runnable() {
        public void run() {

            Dlog.v("Things mIsPollingCancel", mIsPollingCancel);
            Dlog.v("Things mIsPollingPause", mIsPollingPause);
            if (mIsPollingCancel) {
                mScheduledFuture.cancel(false);
            }
            if (!mIsPollingPause) {
                mTotal++;
                mUtil.getTextView(mActivity, R.id.tvConnectTime).post(new Runnable() {
                    @Override
                    public void run() {

                        mUtil.getTextView(mActivity, R.id.tvConnectTime).setText((mMaxTime - mTotal) + "");
                    }
                });
                if (mTotal >= mMaxTime) {
                    if (!mIsEnd) {
                        mIsEnd = true;
                        mUtil.getTextView(mActivity, R.id.tvConnectTime).post(new Runnable() {
                            @Override
                            public void run() {

                                mUtil.getTextView(mActivity, R.id.tvConnectTime).setText("");

                                //실패 화면 호출
                                mUtil.getView(mActivity, R.id.llPageRoot).setVisibility(View.INVISIBLE);
                                mIntent = new Intent(mActivity, ThingsDeviceAddStep4.class);
                                mIntent.putExtra(Constants.EXTRA_DEVICE_NAME, mDeviceName);
                                mIntent.putExtra(Constants.EXTRA_COMPANY_NAME, mCompanyName);
                                mIntent.putExtra(Constants.EXTRA_DEVICE_DEL_DESC, mDeviceDelDesc);
                                mIntent.putExtra(Constants.EXTRA_DEVICE_ADD_DESC, mDeviceAddDesc);
                                mIntent.putExtra(Constants.EXTRA_DEVICE_IMAGE, mDeviceImageId);
                                mIntent.putExtra(Constants.EXTRA_DEVICE_IMAGE1, mDeviceImageId1);
                                mIntent.putExtra(Constants.EXTRA_DEVICE_ID, mDeviceId);
                                mIntent.putExtra(Constants.EXTRA_RESULT, false);
                                mUtil.callActivityForResultNoAnim(mActivity, mIntent, Constants.ACT_THINGS_DEVICE_ADD_STEP4);
                            }
                        });
                        mScheduledFuture.cancel(false);
                    }
                }
            }
        }
    };

    public void recevicedWebSocket(Intent intentReceived) {

        int receivedState = intentReceived.getIntExtra(EXTRA_RESULT_STATE, WebSocketService.WEBSOCKET_RECEIVED_SUCESS);
        if (receivedState == WebSocketService.WEBSOCKET_RECEIVED_SUCESS) {
            try {
                String result = intentReceived.getStringExtra(Constants.EXTRA_RESULT);
                Dlog.v(result);
                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_NODE_REGISTER_RESULT)) {
                    notificationWsNodeRegisterResult(jsonObject);
                } else if (messageType.equals(Constants.WEBSOCKET_TYPE_DEVICE_COMMAND)) {
                    resultWsDeviceCommand(jsonObject);
                } else if (messageType.equals(Constants.WEBSOCKET_TYPE_DEVICE_COMMAND_RESULT)) {
                    notificationWsDeviceCommandResult(jsonObject);
                } else {
                    // TODO: 2016-11-25 : 처리 방법?
                }
            } catch (JSONException ex) {
                ex.printStackTrace();
            }
        } else if (receivedState == WebSocketService.WEBSOCKET_RECEIVED_ERROR) {

            int errorCode = intentReceived.getIntExtra(EXTRA_ERROR_CODE, WebSocketService.WEBSOCKET_CONNECT_TIMEOUT);
            switch (errorCode) {

            }
        }
    }

    ;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

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

        setIsWebSocket(true);

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

        Intent intent = getIntent();
        mDeviceName = intent.getStringExtra(Constants.EXTRA_DEVICE_NAME);
        mCompanyName = intent.getStringExtra(Constants.EXTRA_COMPANY_NAME);
        mDeviceDelDesc = intent.getStringExtra(Constants.EXTRA_DEVICE_DEL_DESC);
        mDeviceAddDesc = intent.getStringExtra(Constants.EXTRA_DEVICE_ADD_DESC);
        mDeviceImageId = intent.getIntExtra(Constants.EXTRA_DEVICE_IMAGE, 0);
        mDeviceImageId1 = intent.getIntExtra(Constants.EXTRA_DEVICE_IMAGE1, 0);
        mDeviceId = intent.getStringExtra(Constants.EXTRA_DEVICE_ID);

        setDisp();
    }

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

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

        mUtil.getTextView(mActivity, R.id.tvDeviceName).setText(mDeviceName);
        mUtil.getTextView(mActivity, R.id.tvDeviceDesc).setText(mDeviceDelDesc);
        mUtil.setImage(mActivity, mDeviceImageId, R.id.ivIconDevice);


        comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_WS_DEVICE_COMMAND_PAIRING_START), Constants.HANDLER_DELAY_MILLIS);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {

        super.onConfigurationChanged(newConfig);
    }

    @Override
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.llBtn2:
//                sendWsDeviceCommand();
                mUtil.getView(mActivity, R.id.llBtn2).setEnabled(false);
                comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_WS_DEVICE_COMMAND_PAIRING_STOP), Constants.HANDLER_DELAY_MILLIS);
                break;
            default:
                break;
        }
    }

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

        switch (msgId) {
            case Constants.MSG999:
            case Constants.MSG836:
                mUtil.getView(mActivity, R.id.llPageRoot).setVisibility(View.INVISIBLE);
                mIntent = new Intent(mActivity, ThingsDeviceAddStep4.class);
                mIntent.putExtra(Constants.EXTRA_DEVICE_NAME, mDeviceName);
                mIntent.putExtra(Constants.EXTRA_COMPANY_NAME, mCompanyName);
                mIntent.putExtra(Constants.EXTRA_DEVICE_DEL_DESC, mDeviceDelDesc);
                mIntent.putExtra(Constants.EXTRA_DEVICE_ADD_DESC, mDeviceAddDesc);
                mIntent.putExtra(Constants.EXTRA_DEVICE_IMAGE, mDeviceImageId);
                mIntent.putExtra(Constants.EXTRA_DEVICE_IMAGE1, mDeviceImageId1);
                mIntent.putExtra(Constants.EXTRA_DEVICE_ID, mDeviceId);
                mIntent.putExtra(Constants.EXTRA_RESULT, false);
                mUtil.callActivityForResultNoAnim(mActivity, mIntent, Constants.ACT_THINGS_DEVICE_ADD_STEP4);
                break;
            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;
        }
    }

    private void onBackPressedFlowEnd(){
        mIntent = new Intent();
        mIntent.putExtra(Constants.EXTRA_FLOW_END_FLAG, true);
        mActivity.setResult(RESULT_CANCELED, mIntent);
        finish();
    }

    @Override
    public void onBackPressed() {

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

    @Override
    public void onResume() {

        super.onResume();

    }

    @Override
    protected void onDestroy() {

        super.onDestroy();
        Dlog.v("onDestroy()");
        if (mScheduledFuture != null) {
            mScheduledFuture.cancel(false);
            mIsPollingPause = true;
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @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_STEP4:
                    mActivity.setResult(RESULT_OK, data);
                    finish();
                    break;
                default:
                    break;
            }
        } else {
            switch (requestCode) {
                case Constants.ACT_THINGS_DEVICE_ADD_STEP4:
                    Boolean isFlowEnd = data.getBooleanExtra(Constants.EXTRA_FLOW_END_FLAG, false);
                    Boolean isEnd = data.getBooleanExtra(Constants.EXTRA_END_FLAG, false);
                    Boolean isRetry = data.getBooleanExtra(Constants.EXTRA_RETRAY_FLAG, false);
//                    Boolean isTimeout = data.getBooleanExtra(Constants.EXTRA_TIMEOUT_FLAG, false);
                    if (isFlowEnd || isEnd) {
                        mActivity.setResult(RESULT_CANCELED, data);
                        finish();
                    } else if (isRetry) {
                        mUtil.getView(mActivity, R.id.llPageRoot).setVisibility(View.VISIBLE);
                        comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_WS_DEVICE_COMMAND_PAIRING_START)
                                , Constants.HANDLER_DELAY_MILLIS);

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


    /**
     * 노드 추가 60초 타이머 스케줄러.
     */
    private void setThingsAddPolling() {

        mTotal = 0;
        Dlog.v("Things setThingsDelPolling");
        ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();

        mIsPollingPause = false;
        mIsPollingCancel = false;
        mScheduledFuture = scheduler.scheduleAtFixedRate(runnable, 1, 1, TimeUnit.SECONDS);
    }

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

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

    /**
     * 서비스 허브에 디바이스 제어(노드 언페어링 시작, 언페어링 중지) 요청 결과.
     *
     * @param jsonResult 결과 json object
     *
     * @exception JSONException json parsing exception
     */
    private void resultWsDeviceCommand(JSONObject jsonResult) throws JSONException {

        if (jsonResult.get(Constants.KEY_RESULT_CODE).equals("00")) {
            String commandType = jsonResult.getString(Constants.KEY_COMMAND_TYPE);
            if (Constants.WEBSOCKET_COMM_TYPE_PAIRING_START.equals(commandType)) {
                mStartCommandId = jsonResult.getString(Constants.KEY_COMMAND_ID);
            } else if (Constants.WEBSOCKET_COMM_TYPE_PAIRING_STOP.equals(commandType)) {
                mStopCommandId = jsonResult.getString(Constants.KEY_COMMAND_ID);
            }
        } else {
            mCustomDialog.msgAlert(mActivity, Constants.MSG836);
            mUtil.getView(mActivity, R.id.llBtn2).setEnabled(true);
        }
    }

    /**
     * 서비스 허브에 디바이스 제어(노드 언페어링 중지) 결과를 푸쉬받는다.
     *
     * @param joResult : 결과 json object
     *
     * @exception JSONException : json parsing exception
     */
    private void notificationWsDeviceCommandResult(JSONObject joResult) throws JSONException {
        try {
            if (joResult.get(Constants.KEY_COMMAND_STATUS).equals("SUCCESS")) {
                if (joResult.get(Constants.KEY_COMMAND_ID).equals(mStartCommandId)) {
                    setThingsAddPolling();
                } else if (joResult.get(Constants.KEY_COMMAND_ID).equals(mStopCommandId)) {
                    mUtil.getTextView(mActivity, R.id.tvConnectTime).setText("");
                    if (mScheduledFuture != null) {
                        mScheduledFuture.cancel(false);
                        mIsPollingPause = true;
                    }
                    onBackPressedFlowEnd();
                }
            } else {
                Dlog.v(joResult.toString());
                String resultCode = mUtil.null2string(joResult.get(Constants.KEY_RESULT_CODE));
                String resultMsg = mUtil.null2string(joResult.get(Constants.KEY_RESULT_MSG));

                if ("401".equals(resultCode)) {
                    mCustomDialog.msgAlert(mActivity, Constants.MSG998, resultMsg);
                } else if ("401-106".equals(resultCode)) {
                    mCustomDialog.msgAlert(mActivity, Constants.MSG997, resultMsg);
                } else {
                    mCustomDialog.msgAlert(mActivity, Constants.MSG999, resultMsg);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            mCustomDialog.msgAlert(mActivity, Constants.MSG807);
        }
        try {
            mUtil.getView(mActivity, R.id.llBtn2).setEnabled(true);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 서비스 허브에서 노드 추가 결과를 푸쉬받는다.
     *
     * @param jsonObject 결과 json object
     */
    private void notificationWsNodeRegisterResult(JSONObject jsonObject) {
        try {
            if (jsonObject.get(Constants.KEY_DEVICE_ID).equals(mDeviceId)) {
//                mUtil.setPreferences(mActivity, Constants.EXTRA_THINGS_ADD_REMOVE_TIME, "");
                mUtil.getTextView(mActivity, R.id.tvConnectTime).setText("");
                if (mScheduledFuture != null) {
                    mScheduledFuture.cancel(false);
                    mIsPollingPause = true;
                }
                String nodeId = mUtil.null2string(jsonObject.get(Constants.KEY_NODE_ID));
                String prdName = mUtil.null2string(jsonObject.get(Constants.KEY_PRD_NAME));
                String prdUserName = mUtil.null2string(jsonObject.get(Constants.KEY_PRD_USER_NAME));
                String deviceName = !prdUserName.equals("") ? prdUserName : prdName;

                mUtil.getView(mActivity, R.id.llPageRoot).setVisibility(View.INVISIBLE);
                mIntent = new Intent(mActivity, ThingsDeviceAddStep4.class);
                mIntent.putExtra(Constants.EXTRA_DEVICE_NAME, mDeviceName);
                mIntent.putExtra(Constants.EXTRA_COMPANY_NAME, mCompanyName);
                mIntent.putExtra(Constants.EXTRA_DEVICE_DEL_DESC, mDeviceDelDesc);
                mIntent.putExtra(Constants.EXTRA_DEVICE_ADD_DESC, mDeviceAddDesc);
                mIntent.putExtra(Constants.EXTRA_DEVICE_IMAGE, mDeviceImageId);
                mIntent.putExtra(Constants.EXTRA_DEVICE_IMAGE1, mDeviceImageId1);
                mIntent.putExtra(Constants.EXTRA_DEVICE_ID, mDeviceId);
                mIntent.putExtra(Constants.EXTRA_NODE_ID, nodeId);
                mIntent.putExtra(Constants.EXTRA_NAME, deviceName);
                mIntent.putExtra(Constants.EXTRA_RESULT, true);
                mUtil.callActivityForResultNoAnim(mActivity, mIntent, Constants.ACT_THINGS_DEVICE_ADD_STEP4);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            mCustomDialog.msgAlert(mActivity, Constants.MSG807);
        }
    }

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

        @Override
        public boolean handleMessage(Message msg) {

            mType = msg.what;
            switch (msg.what) {
                case MSG_COM_WS_DEVICE_COMMAND_PAIRING_START:
                    if (getWebSocketState()) {
                        sendWsDeviceCommand(Constants.WEBSOCKET_COMM_TYPE_PAIRING_START);
                    } else {
                        comHandler.sendMessageDelayed(comHandler.obtainMessage(mType), Constants.HANDLER_DELAY_MILLIS);
                    }
                    break;

                case MSG_COM_WS_DEVICE_COMMAND_PAIRING_STOP:
                    if (getWebSocketState()) {
                        sendWsDeviceCommand(Constants.WEBSOCKET_COMM_TYPE_PAIRING_STOP);
                    } else {
                        comHandler.sendMessageDelayed(comHandler.obtainMessage(mType), Constants.HANDLER_DELAY_MILLIS);
                    }
                    break;
                default:
                    break;
            }
            return true;
        }
    }

}
