/*
 * 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.c_interface.OnDataSendToReslut;
import com.ntels.onecable.admin.common.http.HttpSend;
import com.ntels.onecable.admin.common.http.Response;
import com.ntels.onecable.admin.common.util.Dlog;
import com.ntels.onecable.admin.common.util.Util;
import com.ntels.onecable.admin.common.widget.CustomActivity;
import com.ntels.onecable.admin.view.dialog.CustomDialog;

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;

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

    private static final String TAG = ThingsHomehubAssignPassword.class.getSimpleName();
    private static final int MSG_COM_P_HOMEGRP = 1;
    private static final int MSG_COM_P_DEVICES_DEVICE_ID_OWNERSHIP = 2;
    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 String mPass = "";
    //    private WebSocketService mWebSocketService;
    private boolean mIsBound = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

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

        setIsWebSocket(true);

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

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

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

    @Override
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.llBtn1:
                mPass = mUtil.getEditTextVal(mActivity, R.id.edtPass);
                if ("".equals(mPass)) {
                    mUtil.setShowToast(mActivity, mUtil.getString(mActivity, R.string.layout_things_guide_16)
                            + mUtil.getString(mActivity, R.string.MSG901), Toast.LENGTH_SHORT);
                    return;
                }
                if (mAppConfig.getCtrtGroupId().isEmpty()) {
                    comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_P_HOMEGRP), Constants.HANDLER_DELAY_MILLIS);
                } else {
                    comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_P_DEVICES_DEVICE_ID_OWNERSHIP), Constants
                            .HANDLER_DELAY_MILLIS);
                }
                break;
            case R.id.btnExit:
                onBackPressed();
                break;
            default:
                break;
        }
    }

    @Override
    public void onBackPressed() {

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

    @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;
            case Constants.MSG833:
                if (btnResult == 1) {
                    onBackPressed();
                }
                break;
            default:
                break;
        }
    }

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

    /**
     * 기존 디바이스의 비밀번호를 확인하여 일치하면 소유권을 변경 처리 요청한다.
     */
    private void sendPutDevicesOwnership() {

        try {
            HttpSend httpSend;
            httpSend = new HttpSend(mActivity);
            httpSend.setOnDataSendToReslutEvent(new OnDataSendToReslut() {
                @Override
                public void resultResponse(Response result) {

                    resultPutDevicesOwnership(result);
                }
            });

            httpSend.P_devices_device_id_ownership(mDeviceId, mPass);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 소유권 변경 처리 요청 결과.
     *
     * @param result 결과 data
     */
    private void resultPutDevicesOwnership(Response result) {

        try {
            if (result.getStatusCode() == Response.OK) {
                JSONObject joResult = new JSONObject(result.getContent());
                Dlog.v(joResult.toString());

                String deviceId = mUtil.null2string(joResult.get(Constants.KEY_DEVICE_ID));

                mAppConfig.setSelectHomehubDeviceId(deviceId);

                getWebSocketService().webSocketConnect();

                mIntent = new Intent();
                mActivity.setResult(RESULT_OK, mIntent);
                finish();
            } else {
                JSONObject joResult = new JSONObject(result.getContent());
                Dlog.v(joResult.toString());
//                String errorCode = mUtil.null2string(joResult.get(Constants.KEY_ERR_CODE));
                String resultCode = mUtil.null2string(joResult.get(Constants.KEY_RESULT_CODE));
//                String errorMsg = mUtil.null2string(joResult.get(Constants.KEY_ERR_MSG));
                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 {
                    mUtil.setShowToast(mActivity, resultMsg, Toast.LENGTH_SHORT);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            mCustomDialog.msgAlert(mActivity, Constants.MSG807);
        }
    }

    /**
     * (홈그룹에 속해 있지 않은 회원이 마스터가 되는) 홈그룹을 새로 생성 요청한다.
     */
    private void sendPostHomegrp() {

        try {
            HttpSend httpSend = new HttpSend(mActivity);
            httpSend.setOnDataSendToReslutEvent(new OnDataSendToReslut() {
                @Override
                public void resultResponse(Response result) {

                    resultPostHomegrp(result);
                }
            });
            httpSend.P_homegrp();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * (홈그룹에 속해 있지 않은 회원이 마스터가 되는) 홈그룹 새로 생성 요청 결과.
     *
     * @param result 결과 data
     */
    private void resultPostHomegrp(Response result) {

        try {
            if (result.getStatusCode() == Response.OK) {
                JSONObject joResult = new JSONObject(result.getContent());
                Dlog.v(joResult.toString());

                String homegrpId = mUtil.null2string(joResult.get(Constants.KEY_HOMEGRP_ID));
                mAppConfig.setCtrtGroupId(homegrpId);

                comHandler.sendMessageDelayed(
                        comHandler.obtainMessage(MSG_COM_P_DEVICES_DEVICE_ID_OWNERSHIP),
                        Constants.HANDLER_DELAY_MILLIS);
            } else {
                JSONObject joResult = new JSONObject(result.getContent());
                Dlog.v(joResult.toString());
//                String errorCode = mUtil.null2string(joResult.get(Constants.KEY_ERR_CODE));
                String resultCode = mUtil.null2string(joResult.get(Constants.KEY_RESULT_CODE));
//                String errorMsg = mUtil.null2string(joResult.get(Constants.KEY_ERR_MSG));
                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 {
                    mUtil.setShowToast(mActivity, resultMsg, Toast.LENGTH_SHORT);
                }
            }
        } 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_P_HOMEGRP:
                    sendPostHomegrp();
                    break;
                case MSG_COM_P_DEVICES_DEVICE_ID_OWNERSHIP:
                    sendPutDevicesOwnership();
                    break;

                default:
                    break;
            }
            return true;
        }
    }

}
