/*
 * 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 java.util.HashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

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

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

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

    private static final int CONNECT_MAX_TIME_SEC = 60;

    /*공통*/
    private Activity mActivity;
    private AppConfig mAppConfig;
    private Intent mIntent;
    private ScheduledFuture mScheduledFuture;
    private Util mUtil = new Util();
    private CustomDialog mCustomDialog = new CustomDialog();
    private String mDeviceDesc1 = "";
    private int mDeviceImageId1 = 0;
    private String mDeviceId = "";
    private String mCommandId = "";
    private Boolean mIsEnd = false;
    private Boolean mIsPollingPause = false;
    private Boolean mIsPollingCancel = false;
    private int mMaxTime = CONNECT_MAX_TIME_SEC;
    private int mTotal = 0;
    private WebSocketService mWebSocketService;
    private boolean mIsBound = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

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

        Intent intent = getIntent();
        mDeviceDesc1 = intent.getStringExtra(Constants.EXTRA_DEVICE_DESC1);
        mDeviceImageId1 = intent.getIntExtra(Constants.EXTRA_DEVICE_IMAGE1, 0);
        mCommandId = intent.getStringExtra(Constants.EXTRA_COMMAND_ID);
        mDeviceId = intent.getStringExtra(Constants.EXTRA_DEVICE_ID);

        setDisp();
    }

    @Override
    public void onBackPressed() {

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

    @Override
    public void onResume() {

        super.onResume();

        Dlog.v("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_DEL_3RD:
                    mActivity.setResult(RESULT_OK, data);
                    finish();
                    break;
                default:
                    break;
            }
        }
    }

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

    @Override
    public void onDestroy() {

        super.onDestroy();
        Dlog.v("onDestroy()");
        if (mIsBound) {
            mWebSocketService.removeWebSocketResponse(webSocketResponse);
            unbindService(serviceConnection);
            mIsBound = false;
        }
    }

    @Override
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.llBtn1:
                sendWsDeviceCommand();
                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;
        }
    }

    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_NODE_DELETE_RESULT)) {
                    notificationWsNodeDeleteResult(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();
            }
        }

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

        }
    };

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

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

        mUtil.getTextView(mActivity, R.id.tvDeviceDesc).setText(mDeviceDesc1);
        mUtil.setImage(mActivity, mDeviceImageId1, R.id.ivIconDevice);
        setThingsAddPolling();
    }

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

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

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

    Runnable runnable = new Runnable() {
        public void run() {

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

                        mUtil.getTextView(mActivity, R.id.tvConnectTime)
                                .setText((mMaxTime - mTotal) + "");
                    }
                });
                //                Dlog.v("Things iTotal2", 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("");
                                mIntent = new Intent();
                                mIntent.putExtra(Constants.EXTRA_TIMEOUT_FLAG, true);
                                mActivity.setResult(RESULT_CANCELED, mIntent);
                                finish();
                            }
                        });
                        mScheduledFuture.cancel(false);
                    }
                }
            }
        }
    };

    /**
     * 서비스 허브에 디바이스제어(노드 언페어링 중지)를 요청한다.
     */
    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, mDeviceId);
        sendParams.put(Constants.KEY_COMMAND_TYPE,
                Constants.WEBSOCKET_COMM_TYPE_PAIRING_STOP);
        sendParams.put(Constants.KEY_REQUEST_ID,
                mAppConfig.getiSelect_Servicehub_Request_Id());

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

    /**
     * 서비스 허브에 디바이스 제어(노드 언페어링 중지) 요청 결과.
     *
     * @param jsonResult 결과 json object
     * @throws JSONException json parsing exception
     */
    private void resultWsDeviceCommand(JSONObject jsonResult) throws JSONException {
        if (jsonResult.get(Constants.KEY_RESULT_CODE).equals("00")) {
            mCommandId = jsonResult.getString(Constants.KEY_COMMAND_ID);
        }
    }

    /**
     * 서비스 허브에 디바이스 제어(노드 언페어링 중지) 결과를 푸쉬받는다.
     *
     * @param joResult : 결과 json object
     * @throws JSONException : json parsing exception
     */
    private void notificationWsDeviceCommandResult(JSONObject joResult) throws JSONException {
        try {
            if (joResult.get(Constants.KEY_COMMAND_ID).equals(mCommandId)) {
                if (joResult.get(Constants.KEY_COMMAND_STATUS).equals("SUCCESS")) {
                    onBackPressed();
                } else {
                    Dlog.v(joResult.toString());
                    String errorCode =
                            mUtil.null2string(joResult.get(Constants.KEY_RESULT_CODE));
                    String errorMsg =
                            mUtil.null2string(joResult.get(Constants.KEY_RESULT_MSG));

                    if ("401".equals(errorCode)) {
                        mCustomDialog.msgAlert(mActivity, Constants.MSG998, errorMsg);
                    } else if ("401-106".equals(errorCode)) {
                        mCustomDialog.msgAlert(mActivity, Constants.MSG997, errorMsg);
                    } else {
                        mCustomDialog.msgAlert(mActivity, Constants.MSG000, errorMsg);
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            mCustomDialog.msgAlert(mActivity, Constants.MSG807);
        }
        try {
            mUtil.getView(mActivity, R.id.llBtn1).setEnabled(true);
            mUtil.getView(mActivity, R.id.btnReStart).setEnabled(true);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 서비스 허브에서 노드 삭제 결과를 푸쉬받는다.
     *
     * @param jsonObject 결과 json object
     */
    private void notificationWsNodeDeleteResult(JSONObject jsonObject) {
        try {
            if (jsonObject.get(Constants.KEY_DEVICE_ID).equals(mDeviceId)) {
                mUtil.setPreferences(mActivity, Constants.EXTRA_THINGS_ADD_REMOVE_TIME, "");
                mIntent = new Intent(mActivity, ThingsDeviceDel3rd.class);
                mUtil.callActivityForResult(mActivity, mIntent,
                        Constants.ACT_THINGS_DEVICE_DEL_3RD);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            mCustomDialog.msgAlert(mActivity, Constants.MSG807);
        }
    }

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

                default:
                    break;
            }
            return true;
        }
    }

}

