/*
 * 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.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 com.ntels.onecable.admin.view.dialog.PushDialog;

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.Toast;

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

  private static final int MSG_COM_P_DEVICES_DEVICE_ID_PASSWORD = 1;

  /*통신 관련*/
  private int type = 0;

  /*공통*/
  private Activity mActivity;
  private AppConfig mAppConfig;
  private Intent intent;
  private Util mUtil = new Util();
  private CustomDialog customDialog = new CustomDialog();
  private String newOwnerAuthPassword = "";

  @Override
  public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    mActivity = HomehubPasswordChange.this;
    mAppConfig = (AppConfig) mActivity.getApplicationContext();
    customDialog.setOnMsgAlterToResultEvent(this);

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

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

  }

  @Override
  public void onConfigurationChanged(Configuration newConfig) {

    super.onConfigurationChanged(newConfig);
  }

  @Override
  public void onClick(View view) {

    switch (view.getId()) {
      case R.id.llBtn1:
        newOwnerAuthPassword = mUtil.getEditTextVal(mActivity, R.id.edtPass);
        if (newOwnerAuthPassword.equals("")) {
          mUtil.setShowToast(mActivity, mUtil.getString(mActivity, R.string.MSG829), Toast.LENGTH_SHORT);
          return;
        }
        if (mUtil.getEditTextVal(mActivity, R.id.edtPassConfirm).equals("")) {
          mUtil.setShowToast(mActivity, mUtil.getString(mActivity, R.string.MSG830), Toast.LENGTH_SHORT);
          return;
        }
        if (!newOwnerAuthPassword.equals(mUtil.getEditTextVal(mActivity, R.id.edtPassConfirm))) {
          mUtil.setShowToast(mActivity, mUtil.getString(mActivity, R.string.MSG863)
              + mUtil.getString(mActivity, R.string.MSG902), Toast.LENGTH_SHORT);
          return;
        }
        view.setEnabled(false);
        comHandler.sendMessageDelayed(comHandler.obtainMessage(
            MSG_COM_P_DEVICES_DEVICE_ID_PASSWORD), 10);
        break;
      case R.id.llBtn2:
        onBackPressed();
        break;
      default:
        break;
    }
  }

  Handler comHandler = new Handler(new IncomingHandlerCallBack());

  class IncomingHandlerCallBack implements Handler.Callback {

    @Override
    public boolean handleMessage(Message msg) {

      type = msg.what;
      switch (msg.what) {
        case MSG_COM_P_DEVICES_DEVICE_ID_PASSWORD:
          sendPutDevicesPassword();
          break;

        default:
          break;
      }
      return true;
    }
  }

  /**
   * (소유권을 확인할 때 사용하는) 디바이스 비밀번호를 변경 요청.
   */
  private void sendPutDevicesPassword() {

    try {
      HttpSend httpSend;

      httpSend = new HttpSend(mActivity);

      httpSend.setOnDataSendToReslutEvent(new OnDataSendToReslut() {
        @Override
        public void resultResponse(Response result) {

          resultPutDevicesPassword(result);
        }
      });
      String deviceId = mAppConfig.getSelectHomehubDeviceId();
      httpSend.P_devices_device_id_password(deviceId, newOwnerAuthPassword);
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }

  /**
   * {@link #sendPutDevicesPassword()} 요청 결과.
   *
   * @param response 결과 data
   */
  private void resultPutDevicesPassword(Response response) {

    try {
      if (response.getStatusCode() == 200) {
        mUtil.setShowToast(mActivity, mUtil.getString(mActivity, R.string.MSG859), Toast.LENGTH_SHORT);
        intent = new Intent();
        mActivity.setResult(RESULT_OK, intent);
        finish();
      } else {
        JSONObject joResult = new JSONObject(response.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));

        switch (resultCode) {
          case "401":
            customDialog.msgAlert(mActivity, Constants.MSG998, resultMsg);
            break;
          case "401-106":
            customDialog.msgAlert(mActivity, Constants.MSG997, resultMsg);
            break;
          default:
            customDialog.msgAlert(mActivity, Constants.MSG000, resultMsg);
            break;
        }
      }
    } catch (Exception ex) {
      ex.printStackTrace();
      customDialog.msgAlert(mActivity, Constants.MSG807);
    }
    try {
      mUtil.getView(mActivity, R.id.llBtn1).setEnabled(true);
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }

  @Override
  public void onBackPressed() {

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

  @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(type), 10);
        }
        break;
      default:
        break;
    }
  }
}
