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

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

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.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Toast;

import java.util.HashMap;

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


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

    private static final String TAG = HomehubDel.class.getSimpleName();
    private static final int MSG_COM_WS_DEVICE_DELETE = 1;
    Handler comHandler = new Handler(new IncomingHandlerCallBack());
    /*통신 관련*/
    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 mDeviceId = "";
    //    private WebSocketService mWebSocketService;
    private boolean mIsBound = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

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

        setIsWebSocket(true);

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

        Intent intent = getIntent();
        mDeviceId = intent.getStringExtra(Constants.EXTRA_DEVICE_ID);

        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.getSelectCtrtGroupHomehubOnlineState().equals("ON")) {
                    mUtil.getView(mActivity, R.id.llBtn1).setEnabled(false);
                    comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_WS_DEVICE_DELETE), 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.MSG703: {
                Intent intent = new Intent();
                intent.putExtra(Constants.EXTRA_RELOAD_FLAG, true);
                mActivity.setResult(RESULT_CANCELED, intent);
                finish();
                break;
            }
            case Constants.MSG704: {
                if (btnResult == 1) {
                    comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_WS_DEVICE_DELETE), Constants.HANDLER_DELAY_MILLIS);
                } else {
                    onBackPressed();
                }
                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();

    }

    @Override
    protected void onDestroy() {

        super.onDestroy();

    }

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

    public void recevicedWebSocket(Intent intentReceived) {

        int receivedState = intentReceived.getIntExtra(Constants.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_DEVICE_DELETE_RESULT)) {
//                    notificationWsDeviceCommandResult(jsonObject);
                } else if (messageType.equals(Constants.WEBSOCKET_TYPE_DEVICE_DELETE)) {
                    resultWsDeviceDelete(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) {

            }
            mCustomDialog.msgAlert(mActivity, Constants.MSG807);
        }
    }

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

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

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

    ;

    /**
     * 서비스 허브에 등록된 홈허브 디바이스를 삭제한다.
     */
    private void sendWsDeviceDelete() {
        HashMap<String, Object> sendParams = new HashMap<>();
        sendParams.put(Constants.KEY_MESSAGE_TYPE, Constants.WEBSOCKET_TYPE_DEVICE_DELETE);
        sendParams.put(Constants.KEY_DEVICE_ID, mDeviceId);
        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_DELETE, sendParams);
    }

    /**
     * {@link #sendWsDeviceDelete()} 요청 결과.
     *
     * @param joResult 결과 data
     *
     * @exception JSONException json parsing exception
     */
    private void resultWsDeviceDelete(JSONObject joResult) throws JSONException {
        dialog_dismiss();
        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)) {
            mCustomDialog.msgAlert(mActivity, Constants.MSG703);

        } else {
            final String finalResultMsg = resultMsg;
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
//                    mUtil.setShowToast(mActivity, finalResultMsg, Toast.LENGTH_SHORT);
                    mCustomDialog.msgAlert(mActivity, Constants.MSG704);
                }
            });
        }
    }

    /**
     * 서비스 허브에 디바이스 제어(노드 페어링 모드) 결과를 푸쉬 받는다.
     *
     * @param jsonResult 결과 json object
     *
     * @exception JSONException json parsing exception
     */
    private void notificationWsDeviceDeleteResult(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.getSelectHomehubDeviceId());
//                mUtil.callActivityForResultNoAnim(mActivity, mIntent, Constants.ACT_THINGS_DEVICE_ADD_02);
            } else {
                Dlog.v(jsonResult.toString());
                if (jsonResult.has(Constants.KEY_COMMAND_MESSAGE)) {
                    String resultMsg = mUtil.null2string(jsonResult.get(Constants.KEY_COMMAND_MESSAGE));
                    mCustomDialog.msgAlert(mActivity, Constants.MSG000, resultMsg);
                } 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);
        }
    }

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

        @Override
        public boolean handleMessage(Message msg) {

            mType = msg.what;
            switch (msg.what) {
                case MSG_COM_WS_DEVICE_DELETE:
                    dialog_show();
                    sendWsDeviceDelete();
                    break;

                default:
                    break;
            }
            return true;
        }
    }

}

