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

package com.ntels.onecable.view.mainmore;

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

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 :   Homemode
 * 2. FileName  :   Homemode.java
 * 3. Package   :   com.ntels.onecable.view.mainmore
 * 4. Date      :   2016-12-01
 * 5. Author    :   aaron
 * 6. Comment   :   Initialize
 * </pre>
 */
public class Homemode extends CustomActionBarActivity implements View.OnClickListener,
    CustomDialog.OnMsgAlterToResult {

  private static final int MSG_COM_P_MODES_MODE_ID_CURRENT_MODE = 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 modeId = "";
  private String basicModeCode = "";
  private String modeIcon = "";
  private String modeIcon1 = "";
  private String modeName = "";
  private String modeDelYn = "";
  private String homegrpRuleId = "";

  Boolean isReload = false;

  @Override
  public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

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

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

    if (null != getIntent()) {
      Intent intent = getIntent();
      modeId = intent.getStringExtra(Constants.EXTRA_MODE_ID);
      basicModeCode = intent.getStringExtra(Constants.EXTRA_BASIC_MODE_CODE);
      modeIcon = intent.getStringExtra(Constants.EXTRA_MODE_ICON);
      modeIcon1 = intent.getStringExtra(Constants.EXTRA_MODE_ICON1);
      modeName = intent.getStringExtra(Constants.EXTRA_MODE_NAME);
      modeDelYn = intent.getStringExtra(Constants.EXTRA_MODE_DEL_YN);
      homegrpRuleId = intent.getStringExtra(Constants.EXTRA_HOMEGRP_RULE_ID);
    }

    setDisp();
  }

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

    util.getView(act, R.id.btnModeChange).setOnClickListener(this);
    util.getView(act, R.id.btnModeSetup).setOnClickListener(this);
    util.getView(act, R.id.btnClose).setOnClickListener(this);

    util.setImage(act, modeIcon, util.getImageView(act, R.id.ivModeIcon));
    Dlog.v(modeId, modeId);
    if (basicModeCode.equals("HOME")) {
      util.getTextView(act, R.id.tvTitle)
          .setText(util.getString(act, R.string.layout_mode_detail_03));
      util.getTextView(act, R.id.tvTitle1)
          .setText(util.getString(act, R.string.layout_mode_detail_04));
    } else if (basicModeCode.equals("AWAY")) {
      util.getTextView(act, R.id.tvTitle)
          .setText(util.getString(act, R.string.layout_mode_detail_05));
      util.getTextView(act, R.id.tvTitle1)
          .setText(util.getString(act, R.string.layout_mode_detail_06));
    } else if (basicModeCode.equals("MORNING")) {
      util.getTextView(act, R.id.tvTitle)
          .setText(util.getString(act, R.string.layout_mode_detail_07));
      util.getTextView(act, R.id.tvTitle1)
          .setText(util.getString(act, R.string.layout_mode_detail_08));
    } else if (basicModeCode.equals("NIGHT")) {
      util.getTextView(act, R.id.tvTitle)
          .setText(util.getString(act, R.string.layout_mode_detail_09));
      util.getTextView(act, R.id.tvTitle1)
          .setText(util.getString(act, R.string.layout_mode_detail_10));
    }

    util.getButton(act, R.id.btnModeChange).setText(modeName);

    util.getView(act, R.id.btnModeSetup).setEnabled(true);
    if (appConfig.getSelect_Homegrp_Grade_Code().equals("MAS")) {
      util.getTextView(act, R.id.tvDesc).setVisibility(View.INVISIBLE);
      if (homegrpRuleId.equals("")) {
        util.getTextView(act, R.id.tvDesc).setVisibility(View.VISIBLE);
        util.getTextView(act, R.id.tvDesc)
            .setText(util.getString(act, R.string.layout_mode_detail_01));
      } else if (!modeDelYn.equals("0")) {
        util.getTextView(act, R.id.tvDesc).setVisibility(View.VISIBLE);
        util.getTextView(act, R.id.tvDesc)
            .setText(util.getString(act, R.string.layout_mode_detail_02));
      }
    } else {
      util.getTextView(act, R.id.tvDesc).setVisibility(View.INVISIBLE);
      util.getView(act, R.id.btnModeSetup).setVisibility(View.INVISIBLE);
    }
  }

  @Override
  public void onConfigurationChanged(Configuration newConfig) {

    super.onConfigurationChanged(newConfig);
  }

  @Override
  public void onClick(View view) {

    switch (view.getId()) {
      case R.id.btnModeSetup:
        util.callBtnGoogleAnalytics(act, "Set_Mode", modeName);
        intent = new Intent(act, HomemodeEdit.class);
        intent.putExtra(Constants.EXTRA_MODE_ID, modeId);
        intent.putExtra(Constants.EXTRA_MODE_ICON, modeIcon);
        intent.putExtra(Constants.EXTRA_MODE_ICON1, modeIcon1);
        intent.putExtra(Constants.EXTRA_MODE_NAME, modeName);
        intent.putExtra(Constants.EXTRA_MODE_DEL_YN, modeDelYn);
        intent.putExtra(Constants.EXTRA_HOMEGRP_RULE_ID, homegrpRuleId);
        util.callActivityForResultNoAnim(act, intent, Constants.ACT_HOMEMODE_EDIT);
        break;
      case R.id.btnClose:
        onBackPressed();
        break;
      case R.id.btnModeChange:
        if (appConfig.getSelect_Homegrp_Homehub_Online_State().equals("ON")) {
          util.callBtnGoogleAnalytics(act, "Chage_Mode", modeName);
          util.getView(act, R.id.progressLoading).setVisibility(View.VISIBLE);
          util.getView(act, R.id.btnModeChange).setVisibility(View.INVISIBLE);
          util.getView(act, R.id.ivSucess).setVisibility(View.INVISIBLE);
          util.setVibrator(100);
          comHandler.sendMessageDelayed(comHandler.obtainMessage(
              MSG_COM_P_MODES_MODE_ID_CURRENT_MODE), 10);
        } else {
          util.setShowToast(act, util.getString(act, R.string.MSG866), Toast.LENGTH_SHORT);
          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_MODES_MODE_ID_CURRENT_MODE:
          sendPutCurrentMode();
          break;

        default:
          break;
      }
      return true;
    }
  }

  /**
   * 현재 홈모드 변경(현재 홈모드를 변경한다) 요청.
   */
  private void sendPutCurrentMode() {

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

          resultPutCurrentMode(result);
        }
      });

      //공통 변수 입력
      httpSend.P_modes_mode_id_current_mode(modeId);
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }

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

    try {
      if (response.getStatusCode() == 200) {
        util.getView(act, R.id.btnModeSetup).setEnabled(true);
        util.getImageView(act, R.id.ivModeIcon).setVisibility(View.INVISIBLE);
        util.getTextView(act, R.id.tvTitle)
            .setText(modeName + util.getString(act, R.string.layout_mode_detail_12));
        util.getTextView(act, R.id.tvTitle1).setText("");
        util.getTextView(act, R.id.tvTitle1).setVisibility(View.INVISIBLE);
        util.getView(act, R.id.progressLoading).setVisibility(View.INVISIBLE);
        util.getView(act, R.id.btnModeChange).setVisibility(View.INVISIBLE);
        util.getView(act, R.id.ivSucess).setVisibility(View.VISIBLE);
        isReload = true;
      } else {
        JSONObject joResult = new JSONObject(response.getContent());
        Dlog.v(joResult.toString());
        String errorCode = util.null2string(joResult.get(Constants.KEY_ERR_CODE));
        String errorMsg = util.null2string(joResult.get(Constants.KEY_ERR_MSG));

        if (errorCode.equals("401")) {
          customDialog.msgAlert(act, Constants.MSG998, errorMsg);
        } else if (errorCode.equals("401-106")) {
          customDialog.msgAlert(act, Constants.MSG997, errorMsg);
        } else {
          customDialog.msgAlert(act, Constants.MSG000, errorMsg);
        }
      }
    } catch (Exception ex) {
      ex.printStackTrace();
      customDialog.msgAlert(act, Constants.MSG807);
    }
  }

  @Override
  public void onBackPressed() {

    intent = new Intent();
    intent.putExtra(Constants.EXTRA_RELOAD_FLAG, isReload);
    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;
    }
  }

  @Override
  public void onActivityResult(int requestCode, int resultCode, Intent data) {

    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {
      switch (requestCode) {
        case Constants.ACT_HOMEMODE_EDIT:
          isReload = true;
          modeDelYn = util.null2string(data.getStringExtra(Constants.EXTRA_MODE_DEL_YN));
          homegrpRuleId = util.null2string(data.getStringExtra(Constants.EXTRA_HOMEGRP_RULE_ID));
          setDisp();
          break;
        default:
          break;
      }
    } else {
      switch (requestCode) {
        default:
          break;
      }
    }
  }
}
