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

package com.ntels.kneet.v3.view.mainmore;

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;

import com.ntels.kneet.v3.R;
import com.ntels.kneet.v3.common.AppConfig;
import com.ntels.kneet.v3.common.Constants;
import com.ntels.kneet.v3.common.c_interface.OnDataSendToReslut;
import com.ntels.kneet.v3.common.http.HttpSend;
import com.ntels.kneet.v3.common.http.Response;
import com.ntels.kneet.v3.common.util.Dlog;
import com.ntels.kneet.v3.common.util.Util;
import com.ntels.kneet.v3.common.widget.CustomActivity;
import com.ntels.kneet.v3.view.dialog.CustomDialog;

import org.json.JSONObject;

/**
 * <pre>
 * 1. ClassName :   HomehubPasswordChange
 * 2. FileName  :   HomehubPasswordChange.java
 * 3. Package   :   com.ntels.kneet.v3.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 act;
  private AppConfig appConfig;
  private Intent intent;
  private Util util = new Util();
  private CustomDialog customDialog = new CustomDialog();
  private String newOwnerAuthPassword = "";

  @Override
  public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    act = HomehubPasswordChange.this;
    appConfig = (AppConfig) act.getApplicationContext();
    customDialog.setOnMsgAlterToResultEvent(this);

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

    util.getView(act, R.id.llBtn1).setOnClickListener(this);
    util.getView(act, 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 = util.getEditTextVal(act, R.id.edtPass);
        if (newOwnerAuthPassword.equals("")) {
          util.setShowToast(act, util.getString(act, R.string.MSG829), Toast.LENGTH_SHORT);
          return;
        }
        if (util.getEditTextVal(act, R.id.edtPassConfirm).equals("")) {
          util.setShowToast(act, util.getString(act, R.string.MSG830), Toast.LENGTH_SHORT);
          return;
        }
        if (!newOwnerAuthPassword.equals(util.getEditTextVal(act, R.id.edtPassConfirm))) {
          util.setShowToast(act, util.getString(act, R.string.MSG863)
              + util.getString(act, 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(act);

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

          resultPutDevicesPassword(result);
        }
      });
      String deviceId = appConfig.getSelect_Homegrp_Homehub_Device_Id();
      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) {
        util.setShowToast(act, util.getString(act, R.string.MSG859), Toast.LENGTH_SHORT);
        intent = new Intent();
        act.setResult(RESULT_OK, intent);
        finish();
      } else {
        JSONObject joResult = new JSONObject(response.getContent());
        Dlog.v(joResult.toString());
        String errorCode = util.null2string(joResult.get(Constants.HTTP_err_code));
        String errorMsg = util.null2string(joResult.get(Constants.HTTP_err_msg));

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

  @Override
  public void onBackPressed() {

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

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

    switch (msgId) {

      case Constants.MSG998:
        util.callApp_Start(act, "LOGOUT");
        break;
      case Constants.MSG997:
        util.callApp_Start(act, "HOME_RELOAD");
        break;
      case Constants.MSG807:
        if (btnResult == 1) {
          comHandler.sendMessageDelayed(comHandler.obtainMessage(type), 10);
        }
        break;
      default:
        break;
    }
  }
}
