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

package com.ntels.onecable.view.rules;

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.CustomActivity;
import com.ntels.onecable.view.dialog.CustomDialog;
import com.ntels.onecable.view.dialog.DialogSpinner;

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 java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;

import butterknife.ButterKnife;
import butterknife.OnClick;

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

  private static final int MSG_COM_G_MODES = 1;

  private Util mUtil = new Util();
  private Intent mIntent;
  private Activity mActivity;

  private ArrayList<HashMap<String, Object>> mConditionList = new ArrayList<>();
  private ArrayList<HashMap<String, Object>> mActionList = new ArrayList<>();
  private ArrayList<HashMap<String, Object>> mTriggerList = new ArrayList<>();
  private ArrayList<String> mModeIds = new ArrayList<>();
  private ArrayList<String> mModeTitles = new ArrayList<>();
  private ArrayList<String> mModeResults = new ArrayList<>();
  private String mMode = "";
  private String mModeCode = "";
  private int mModeType = 2;
  private int mModePosition = -1;

  Handler mComHandler = new Handler(new IncomingHandlerCallBack());
  private int mType;

  private CustomDialog mCustomDialog = new CustomDialog();

  @Override
  public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    mActivity = RulesConditionSelect.this;
    mCustomDialog.setOnMsgAlterToResultEvent(this);

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

    ButterKnife.bind(this);

    if (null != getIntent()) {
      mTriggerList = (ArrayList<HashMap<String, Object>>) getIntent().getSerializableExtra(Constants.EXTRA_TRIGGERS);
      mConditionList = (ArrayList<HashMap<String, Object>>) getIntent().getSerializableExtra(Constants.EXTRA_CONDITIONS);
      mActionList = (ArrayList<HashMap<String, Object>>) getIntent().getSerializableExtra(Constants.EXTRA_ACTIONS);
    }

    displayListView();
  }

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

  }

  @OnClick({R.id.llConditionMode, R.id.llConditionDate, R.id.llConditionThings, R.id.llBtn2})
  public void onClick(View view) {

    switch (view.getId()) {
      case R.id.llConditionMode:
        mUtil.callBtnGoogleAnalytics(mActivity, "Set_Condition", "Condi_Homemode");
        /*mMode = "";
        mModeCode = "";
        mModePosition = -1;
        mModeResults.clear();
        callModeSpinner();*/
        mIntent = new Intent();
        mIntent.putExtra(Constants.EXTRA_CONDITION_TYPE, Constants.ACT_SPINNER);
        setResult(RESULT_OK, mIntent);
        finish();
        break;
      case R.id.llConditionDate:
          mUtil.callBtnGoogleAnalytics(mActivity, "Set_Condition", "Condi_Period");
          mIntent = new Intent(mActivity, RulesDateSelect.class);
          mIntent.putExtra(Constants.EXTRA_DATE, "");
          mUtil.callActivityForResultNoAnim(mActivity, mIntent, Constants.ACT_RULES_DATE_SELECT);
        break;
      case R.id.llConditionThings:
        mUtil.callBtnGoogleAnalytics(mActivity, "Set_Condition", "Condi_Things");
        mIntent = new Intent(mActivity, RulesThingsSelect.class);
        mIntent.putExtra(Constants.EXTRA_CALL_TYPE, "3");
        mIntent.putExtra(Constants.EXTRA_TRIGGERS, mTriggerList);
        mIntent.putExtra(Constants.EXTRA_ACTIONS, mActionList);
        mIntent.putExtra(Constants.EXTRA_CONDITIONS, mConditionList);
        mUtil.callActivityForResultNoAnim(mActivity, mIntent, Constants.ACT_RULES_THINGS_SELECT);
        break;
      case R.id.llBtn2:
        onBackPressed();
        break;
      default:
        break;
    }
  }

  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    data.putExtra(Constants.EXTRA_CONDITION_TYPE, requestCode);
    setResult(resultCode, data);
    finish();
  }

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

    switch (msgId) {

      case Constants.MSG841:
        break;
      case Constants.MSG842:
        break;
      case Constants.MSG807:
        if (btnResult == 1) {
          mComHandler.sendMessageDelayed(mComHandler.obtainMessage(mType), Constants.HANDLER_DELAY_MILLIS);
        }
        break;
      default:
        break;
    }
  }

  @Override
  public void onBackPressed() {

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

  /**
   * Spinner display.
   */
  void callModeSpinner() {

    if (mModeIds.size() > 0) {
      if (!"".equals(mModeCode)) {
        mModeResults.clear();
        String[] strArray = mModeCode.split("\\,", 100);
        for (String s : strArray) {
          for (int row1 = 0; row1 < mModeIds.size(); row1++) {
            if (s.equals(mModeIds.get(row1))) {
              mModeResults.add("" + row1);
              break;
            }
          }
        }
      } else {
        for (int row1 = 0; row1 < mModeIds.size(); row1++) {
          mModeResults.add("" + row1);
        }
      }

      mIntent = new Intent();
      mIntent.setClass(mActivity, DialogSpinner.class);
      mIntent.putExtra(Constants.EXTRA_SPINNER_LIST1, mModeTitles);
      if (AppConfig.getLanguageType().equalsIgnoreCase(Locale.ENGLISH.toString())) {
        mIntent.putExtra(Constants.EXTRA_SPINNER_TITLE, mUtil.getString(mActivity, R.string.layout_rules_edit_08).substring(4));
      } else {
        mIntent.putExtra(Constants.EXTRA_SPINNER_TITLE, mUtil.getString(mActivity, R.string.layout_rules_edit_08));
      }
      mIntent.putExtra(Constants.EXTRA_SPINNER_TYPE, mModeType);
      if (mModeType == 2) {
        mIntent.putExtra(Constants.EXTRA_SPINNER_POSITION_LIST, mModeResults);
      } else {
        mIntent.putExtra(Constants.EXTRA_SPINNER_POSITION, mModePosition);
      }
      mUtil.callActivityForResultNoAnim(mActivity, mIntent, Constants.ACT_SPINNER);
    } else {
      mComHandler.sendMessage(mComHandler.obtainMessage(MSG_COM_G_MODES));
    }
  }

  /**
   * 홈모드 조회(홈그룹의 홈모드 목록을 불러온다) 요청.
   */
  private void sendGetModes() {

    try {
      HttpSend httpSend;

      httpSend = new HttpSend(mActivity);

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

          resultGetModes(result);
        }
      });
      httpSend.getModes();
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }

  /**
   * 홈모드 조회(홈그룹의 홈모드 목록을 불러온다) 요청 결과.
   *
   * @param result 결과 data
   */
  private void resultGetModes(Response result) {

    try {
      if (result.getStatusCode() == 200) {
        ArrayList<HashMap<String, Object>> alList = mUtil.jsonToArrayListMap(result.getContent());
        if (alList.size() > 0) {
          for (int row = 0; row < alList.size(); row++) {
            HashMap<String, Object> hmTemp;
            hmTemp = alList.get(row);
            String modeId = mUtil.null2string(hmTemp.get(Constants.KEY_MODE_ID));
            String modeName = mUtil.null2string(hmTemp.get(Constants.KEY_MODE_NAME));
            mModeIds.add(modeId);
            mModeTitles.add(modeName);
          }
        }
        callModeSpinner();
      } 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));

        switch (resultCode) {
          case "401":
            mCustomDialog.msgAlert(mActivity, Constants.MSG998, resultMsg);
            break;
          case "401-106":
            mCustomDialog.msgAlert(mActivity, Constants.MSG997, resultMsg);
            break;
          default:
            mCustomDialog.msgAlert(mActivity, Constants.MSG000, resultMsg);
            break;
        }
      }
    } 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_G_MODES:
          sendGetModes();
          break;
        default:
          break;
      }
      return true;
    }
  }

}
