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

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

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 com.ntels.onecable.admin.view.things.ThingsDeviceAddStep2;

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.support.v7.widget.Toolbar;
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 HomehubUpdateLoading extends CustomActivity implements View.OnClickListener,
        CustomDialog.OnMsgAlterToResult {

    private static final String TAG = HomehubUpdateLoading.class.getSimpleName();
    private static final int MSG_COM_WS_FIRMWARE_UPGRADE = 1;
    private static final int MSG_COM_WS_SOFTWARE_UPGRADE = 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 Toolbar mToolbar;
    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 int mCallType = 0;
    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, ThingsDeviceAddStep2.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_STEP2);
                            }
                        });
                        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);

                switch (messageType) {
                    case Constants.WEBSOCKET_TYPE_FIRMWARE_UPGRADE:
                        resultWsFirmwareUpgradeCommand(jsonObject);
                        break;
                    case Constants.WEBSOCKET_TYPE_FIRMWARE_UPGRADE_RESULT:
                        notificationWsFirmwareUpgradeResult(jsonObject);
                        break;
                    case Constants.WEBSOCKET_TYPE_SOFTWARE_UPGRADE:
                        resultWsSoftwareUpgradeCommand(jsonObject);
                        break;
                    case Constants.WEBSOCKET_TYPE_SOFTWARE_UPGRADE_RESULT:
                        notificationWsSoftwareUpgradeResult(jsonObject);
                        break;
                }
            } 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 = HomehubUpdateLoading.this;
        mAppConfig = (AppConfig) mActivity.getApplicationContext();
        mCustomDialog.setOnMsgAlterToResultEvent(this);

        setIsWebSocket(true);

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

        Intent intent = getIntent();
        Dlog.v("getIntent() = " + getIntent());
        mDeviceId = intent.getStringExtra(Constants.EXTRA_DEVICE_ID);
        mCallType = intent.getIntExtra(Constants.EXTRA_CALL_TYPE, Constants.HOMEHUB_FIRMWARE_UPDATE);

        setToolbar();
        setDisp();
    }

    /**
     * 툴바 셋팅.
     */
    private void setToolbar() {

        mToolbar = (Toolbar) mActivity.findViewById(R.id.toolbar);
        mUtil.setKeyboardHide(mActivity, mToolbar);
        mUtil.getTextView(mToolbar, R.id.tvToolbarTitle1).setVisibility(View.VISIBLE);
        mUtil.getTextView(mToolbar, R.id.tvToolbarTitle2).setVisibility(View.GONE);
        mUtil.getTextView(mToolbar, R.id.tvToolbarTitleDivider).setVisibility(View.GONE);
        mUtil.getTextView(mToolbar, R.id.tvToolbarTitle3).setVisibility(View.GONE);
        mUtil.getTextView(mToolbar, R.id.tvToolbarTitle4).setVisibility(View.GONE);
        mUtil.getTextView(mToolbar, R.id.btnToolbarClose).setVisibility(View.GONE);
        mUtil.getTextView(mToolbar, R.id.btnToolbarModify).setVisibility(View.GONE);
        mUtil.getTextView(mToolbar, R.id.btnToolbarMore).setVisibility(View.GONE);

        mUtil.getTextView(mToolbar, R.id.tvToolbarTitle1).setText(mUtil.getString(mActivity, R.string.layout_homehub_update_loading_01));

    }

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

//        setThingsDelPolling();
        if (mCallType == Constants.HOMEHUB_FIRMWARE_UPDATE) {
            comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_WS_FIRMWARE_UPGRADE), Constants.HANDLER_DELAY_MILLIS);
        } else if (mCallType == Constants.HOMEHUB_SOFTWARE_UPDATE) {
            comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_WS_SOFTWARE_UPGRADE), 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_UNPAIRING_STOP), Constants
//                        .HANDLER_DELAY_MILLIS);
//                break;
            default:
                break;
        }
    }

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

        switch (msgId) {
            case Constants.MSG999:
            case Constants.MSG836:
                onBackPressed();
                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();
    }

    private void onBackPressedEnd() {
        mIntent = new Intent();
        mIntent.putExtra(Constants.EXTRA_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_STEP2:
                    mActivity.setResult(RESULT_OK, data);
                    finish();
                    break;
                default:
                    break;
            }
        } else {
            switch (requestCode) {
//                case Constants.ACT_THINGS_DEVICE_ADD_STEP2:
//                    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_UNPAIRING_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 setThingsUpdatePolling() {

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

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

    /**
     * 서비스 허브에 펌웨어 업그레이드를 요청한다.
     */
    private void sendWsFirmwareUpgradeCommand() {
        HashMap<String, Object> sendParams = new HashMap<>();
        sendParams.put(Constants.KEY_MESSAGE_TYPE, Constants.WEBSOCKET_TYPE_FIRMWARE_UPGRADE);
        sendParams.put(Constants.KEY_CUST_ID, mAppConfig.getCustId());
        sendParams.put(Constants.KEY_CTRT_GRP_ID, mAppConfig.getCtrtGroupId());
        sendParams.put(Constants.KEY_DEVICE_ID, mDeviceId);
        sendParams.put(Constants.KEY_REQUEST_ID, mAppConfig.getSelectServicehubRequestId());

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

    /**
     * {@link #sendWsFirmwareUpgradeCommand() 노드 제어} 요청 결과.
     *
     * @param joResult 결과 json object
     *
     * @exception JSONException json parsing exception
     */
    private void resultWsFirmwareUpgradeCommand(JSONObject joResult) throws JSONException {

        String resultCode = mUtil.null2string(joResult.get(Constants.KEY_RESULT_CODE));
        if (resultCode.equals("00")) {
//            mCommandId = joResult.getString(Constants.KEY_COMMAND_ID);
            setThingsUpdatePolling();
        } else {
//            mUtil.setShowToast(mActivity, mUtil.getString(mActivity, R.string.MSG836), Toast.LENGTH_SHORT);
//            mCustomDialog.msgAlert(mActivity, Constants.MSG933);
            Dlog.v(joResult.toString());
            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);
            }
        }
    }

    /**
     * 서비스 허브에 디바이스 제어(노드 언페어링 중지) 결과를 푸쉬받는다.
     *
     * @param joResult : 결과 json object
     *
     * @exception JSONException : json parsing exception
     */
    private void notificationWsFirmwareUpgradeResult(JSONObject joResult) throws JSONException {
        try {

            dialog_dismiss();
            String resultCode = mUtil.null2string(joResult.get(Constants.KEY_RESULT_CODE));
            if (resultCode.equals("00")) {

//                mFirmwareUpdate.setEnabled(true);
//                mFirmwareUpdate.setVisibility(View.GONE);
                mCustomDialog.msgAlert(mActivity, Constants.MSG932);
            } else {
                Dlog.v(joResult.toString());
                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();
//        }
    }

    /**
     * 서비스 허브에 소프트웨어 업그레이드를 요청한다.
     */
    private void sendWsSoftwareUpgradeCommand() {
        HashMap<String, Object> sendParams = new HashMap<>();
        sendParams.put(Constants.KEY_MESSAGE_TYPE, Constants.WEBSOCKET_TYPE_SOFTWARE_UPGRADE);
        sendParams.put(Constants.KEY_CUST_ID, mAppConfig.getCustId());
        sendParams.put(Constants.KEY_CTRT_GRP_ID, mAppConfig.getCtrtGroupId());
        sendParams.put(Constants.KEY_DEVICE_ID, mDeviceId);
        sendParams.put(Constants.KEY_REQUEST_ID, mAppConfig.getSelectServicehubRequestId());

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

    /**
     * {@link #sendWsFirmwareUpgradeCommand() 노드 제어} 요청 결과.
     *
     * @param joResult 결과 json object
     *
     * @exception JSONException json parsing exception
     */
    private void resultWsSoftwareUpgradeCommand(JSONObject joResult) throws JSONException {

        String resultCode = mUtil.null2string(joResult.get(Constants.KEY_RESULT_CODE));
        if (resultCode.equals("00")) {
            setThingsUpdatePolling();
        } else {
//            mUtil.setShowToast(mActivity, mUtil.getString(mActivity, R.string.MSG836), Toast.LENGTH_SHORT);
//            mCustomDialog.msgAlert(mActivity, Constants.MSG933);
            Dlog.v(joResult.toString());
            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);
            }
        }
    }

    /**
     * 서비스 허브에 디바이스 제어(노드 언페어링 중지) 결과를 푸쉬받는다.
     *
     * @param joResult : 결과 json object
     *
     * @exception JSONException : json parsing exception
     */
    private void notificationWsSoftwareUpgradeResult(JSONObject joResult) throws JSONException {
        try {

            dialog_dismiss();
            String resultCode = mUtil.null2string(joResult.get(Constants.KEY_RESULT_CODE));
            if (resultCode.equals("00")) {

//                mSoftwareUpdate.setEnabled(true);
//                mSoftwareUpdate.setVisibility(View.GONE);
                mCustomDialog.msgAlert(mActivity, Constants.MSG932);
            } else {
                Dlog.v(joResult.toString());
                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();
//        }
    }


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

        @Override
        public boolean handleMessage(Message msg) {

            mType = msg.what;
            switch (msg.what) {

                case MSG_COM_WS_SOFTWARE_UPGRADE:
                    if (getWebSocketState()) {
                        sendWsSoftwareUpgradeCommand();
                    } else {
                        comHandler.sendMessageDelayed(comHandler.obtainMessage(mType), Constants.HANDLER_DELAY_MILLIS);
                    }
                    break;
                case MSG_COM_WS_FIRMWARE_UPGRADE:
                    if (getWebSocketState()) {
                        sendWsFirmwareUpgradeCommand();
                    } else {
                        comHandler.sendMessageDelayed(comHandler.obtainMessage(mType), Constants.HANDLER_DELAY_MILLIS);
                    }
                    break;

                default:
                    break;
            }
            return true;
        }
    }

}
