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

package com.ntels.onecable.view.mainmore;

import com.ntels.onecable.R;
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 com.ntels.onecable.view.rules.RulesThingsSelect;

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.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;

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

  private static final int MSG_COM_P_MODE_SCENES_MODE_ID = 1;
  private static final int MSG_COM_G_MODE_SCENES_MODE_ID = 2;
  private static final int MSG_COM_D_MODES_MODE_ID_RULE = 3;

  private ArrayList<HashMap<String, Object>> conditions = new ArrayList<>();
  private ArrayList<HashMap<String, Object>> actions = new ArrayList<>();
  private ArrayList<HashMap<String, Object>> triggers = new ArrayList<>();

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


  /*공통*/
  private Activity act;
  private Intent intent;
  private Util util = new Util();
  private CustomDialog customDialog = new CustomDialog();
  private Boolean isRuleDeleteAll = false;
  private String modeId = "";
  private String modeName = "";
  private String modeIcon1 = "";
  private String modeDelYn = "";
  private String homegrpRuleId = "";

  @Override
  public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    act = HomemodeEdit.this;
    customDialog.setOnMsgAlterToResultEvent(this);

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

    if (null != getIntent()) {
      Intent intent = getIntent();
      modeId = intent.getStringExtra(Constants.EXTRA_MODE_ID);
      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);
    }

    setToolbar();
    setDisp();
  }

  /**
   * 툴바 셋팅.
   */
  private void setToolbar() {

    Toolbar toolbar = (Toolbar) act.findViewById(R.id.toolbar);
    util.setKeyboardHide(act, toolbar);
    util.getTextView(toolbar, R.id.tvToolbarTitle1).setVisibility(View.VISIBLE);
    util.getTextView(toolbar, R.id.tvToolbarTitle2).setVisibility(View.GONE);
    util.getTextView(toolbar, R.id.tvToolbarTitleDivider).setVisibility(View.GONE);
    util.getTextView(toolbar, R.id.tvToolbarTitle3).setVisibility(View.GONE);
    util.getTextView(toolbar, R.id.tvToolbarTitle4).setVisibility(View.GONE);
    util.getTextView(toolbar, R.id.btnToolbarDel).setVisibility(View.GONE);
    util.getTextView(toolbar, R.id.btnToolbarClose).setVisibility(View.GONE);
    util.getTextView(toolbar, R.id.btnToolbarMore).setVisibility(View.GONE);

    util.getTextView(toolbar, R.id.tvToolbarTitle1)
        .setText(util.getString(act, R.string.layout_mode_edit_01));
  }

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

    util.getView(act, R.id.llActionAdd).setOnClickListener(this);

    util.getView(act, R.id.llBtn1).setOnClickListener(this);
    util.getView(act, R.id.llBtn2).setOnClickListener(this);

    util.setKeyboardHide(act, util.getLinearLayout(act, R.id.llPageRoot));
    util.setKeyboardHide(act, util.getLinearLayout(act, R.id.llSvbody));

    util.getTextView(act, R.id.tvTitle).setText(modeName);
    util.setImage(act, modeIcon1, util.getImageView(act, R.id.ivModeIcon));

    if (!homegrpRuleId.equals("")) {
      comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_G_MODE_SCENES_MODE_ID), 10);
    }
  }

  @Override
  public void onConfigurationChanged(Configuration newConfig) {

    super.onConfigurationChanged(newConfig);
  }

  @SuppressWarnings("unchecked")
  @Override
  public void onClick(View view) {

    switch (view.getId()) {
      case R.id.llBtn1:
        if (!modeDelYn.equals("0")) {
          Boolean isCheck = false;
          if (!isCheck) {
            if (actions.size() > 0) {
              for (int row = 0; row < actions.size(); row++) {
                ArrayList<HashMap<String, Object>> tempItemSubList =
                    (ArrayList<HashMap<String, Object>>) actions.get(row)
                        .get(Constants.KEY_ITEM_SUB);

                for (int row1 = 0; row1 < tempItemSubList.size(); row1++) {
                  String availableYn = util.null2string(
                      tempItemSubList.get(row1).get(Constants.KEY_AVAILABLE_YN));
                  if (availableYn.equals("N")) {
                    isCheck = true;
                    break;
                  }
                }
              }
            }
          }

          if (isCheck) {
            customDialog.msgAlert(act, Constants.MSG875);
            return;
          }
        }
        if (isRuleDeleteAll) {
          // 기존에 설정되있던 규칙들을 모두 삭제 시 모드 규칙 삭제 API 수행
          comHandler.sendMessage(comHandler.obtainMessage(MSG_COM_D_MODES_MODE_ID_RULE));
        } else if (actions.size() > 0) {
          // 모드 규칙 등록 및 수정 API 수행
          comHandler.sendMessage(comHandler.obtainMessage(MSG_COM_P_MODE_SCENES_MODE_ID));
        } else {
          // 아무 변화 없을 시
          onBackPressed();
        }
        break;
      case R.id.llBtn2:
        onBackPressed();
        break;
      case R.id.llActionAdd:
        intent = new Intent(act, RulesThingsSelect.class);
        intent.putExtra(Constants.EXTRA_CALL_TYPE, "4");
        intent.putExtra(Constants.EXTRA_ACTIONS, actions);
        util.callActivityForResultNoAnim(act, intent, Constants.ACT_RULES_THINGS_SELECT);
        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_MODE_SCENES_MODE_ID:
          sendPostModeScenes();
          break;
        case MSG_COM_G_MODE_SCENES_MODE_ID:
          sendGetModeScenes();
          break;
        case MSG_COM_D_MODES_MODE_ID_RULE:
          sendDeleteModesRule();
          break;

        default:
          break;
      }
      return true;
    }
  }

  /**
   * 홈그룹 모드의 멀티제어 상세 조회(해당 홈모드 멀티제어의 정보를 상세 조회한다) 요청.
   */
  private void sendGetModeScenes() {

    try {
      HttpSend httpSend;

      httpSend = new HttpSend(act);

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

          resultGetModeScenes(result);
        }
      });
      httpSend.G_mode_scenes_mode_id(modeId);
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }

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

    try {
      if (response.getStatusCode() == 200) {
        ArrayList<HashMap<String, Object>> alList = util.jsonToArrayListMap(response.getContent());
        if (alList.size() > 0) {
          HashMap<String, Object> hmTempActions = new HashMap<String, Object>();
          ArrayList<HashMap<String, Object>> itemSubList = new ArrayList<HashMap<String, Object>>();
          for (int row = 0; row < alList.size(); row++) {
            HashMap<String, Object> tempMap;
            tempMap = alList.get(row);
            //액션이 아예 없는 경우
            itemSubList.add(tempMap);
          }
          hmTempActions.put(Constants.KEY_ITEM_NAME,
              util.getString(act, R.string.layout_rules_detail_03));
          hmTempActions.put(Constants.KEY_ITEM_SUB_TYPE_CODE, "01");
          hmTempActions.put(Constants.KEY_ITEM_SUB, itemSubList);
          actions.add(hmTempActions);
        }
        setDispActions();
      } 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);
    }
  }

  /**
   * 홈그룹 모드의 멀티제어 등록&수정(멀티제어를 등록&수정한다) 요청.
   */
  private void sendPostModeScenes() {

    try {
      HttpSend httpSend;

      httpSend = new HttpSend(act);

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

          resultPostModeScenes(result);
        }
      });

      HashMap<String, Object> hmTemp;
      Dlog.v("actions = " + actions.size());
      hmTemp = actions.get(0);

      Dlog.v(util.MapToJson(hmTemp));

      httpSend.P_mode_scenes_mode_id(modeId, util.MapToJson(hmTemp));
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }

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

    try {
      if (response.getStatusCode() == 200) {
        JSONObject joResult = new JSONObject(response.getContent());

        String homegrpRuleId = util.null2string(joResult.get(Constants.KEY_HOMEGRP_RULE_ID));
        intent = new Intent();
        intent.putExtra(Constants.EXTRA_MODE_DEL_YN, modeDelYn);
        intent.putExtra(Constants.EXTRA_HOMEGRP_RULE_ID, homegrpRuleId);
        act.setResult(RESULT_OK, intent);
        finish();
      } 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);
    }
  }

  /**
   * 홈그룹 모드의 규칙 삭제 요청.
   */
  private void sendDeleteModesRule() {

    try {
      HttpSend httpSend;

      httpSend = new HttpSend(act);

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

          resultDeleteModesRule(result);
        }
      });

      httpSend.D_modes_mode_id_rule(modeId);
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }

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

    try {
      if (response.getStatusCode() == 200) {
        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.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();
    act.setResult(RESULT_CANCELED, intent);
    finish();
  }

  @SuppressWarnings("unchecked")
  @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;
      case Constants.MSG875:
        if (btnResult == 1) {

          if (actions.size() > 0) {
            for (int row = 0; row < actions.size(); row++) {
              ArrayList<HashMap<String, Object>> tempItemSubList =
                  (ArrayList<HashMap<String, Object>>) actions.get(row)
                      .get(Constants.KEY_ITEM_SUB);

              for (int row1 = tempItemSubList.size() - 1; row1 >= 0; row1--) {
                String availableYn = util.null2string(
                    tempItemSubList.get(row1).get(Constants.KEY_AVAILABLE_YN));
                if (availableYn.equals("N")) {
                  tempItemSubList.remove(row1);
                  if (tempItemSubList.size() == 0) {
                    actions.remove(row);
                  }
                }
              }
            }
          }
          modeDelYn = "0";
          setDispActions();
          util.getView(act, R.id.llBtn1).performClick();
        }
        break;
      default:
        break;
    }
  }

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

    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {
      switch (requestCode) {
        case Constants.ACT_RULES_THINGS_SELECT:
          actions = (ArrayList<HashMap<String, Object>>)
              data.getSerializableExtra(Constants.EXTRA_ACTIONS);
          isRuleDeleteAll = false;
          setDispActions();
          break;
        default:
          break;
      }
    } else {
      switch (requestCode) {
        default:
          break;
      }
    }
  }

  /**
   * Actions display.
   */
  @SuppressWarnings("unchecked")
  void setDispActions() {

    Dlog.v("alList_Actions1 = ", actions.toString());
    util.getLinearLayout(act, R.id.llAction).setVisibility(View.VISIBLE);
    util.getLinearLayout(act, R.id.llActionBody).removeAllViews();

    if (actions.size() > 0) {
      for (int row = 0; row < actions.size(); row++) {
        HashMap<String, Object> tempMap;
        tempMap = actions.get(row);

        String itemSubTypeCode = util.null2string(tempMap.get(Constants.KEY_ITEM_SUB_TYPE_CODE));

        ArrayList<HashMap<String, Object>> itemSubList;
        if (!util.null2string(tempMap.get(Constants.KEY_ITEM_SUB)).equals("")) {
          itemSubList = (ArrayList<HashMap<String, Object>>) tempMap.get(Constants.KEY_ITEM_SUB);
          if (itemSubTypeCode.equals("01")) {
            for (int row1 = 0; row1 < itemSubList.size(); row1++) {
              LinearLayout childView = (LinearLayout) View.inflate(
                  this, R.layout.row_rules_actions_list, null);

              util.getView(childView, R.id.llRowRoot).setTag(row1);
              util.getView(childView, R.id.llRowRoot)
                  .setOnClickListener(new View.OnClickListener() {
                    int tag = 0;

                    @Override
                    public void onClick(View view) {

                      tag = (int) view.getTag();

                      for (int row = 0; row < actions.size(); row++) {
                        String itemSubTypeCode = util.null2string(
                            actions.get(row).get(Constants.KEY_ITEM_SUB_TYPE_CODE));
                        if (!util.null2string(
                            actions.get(row).get(Constants.KEY_ITEM_SUB)).equals("")) {
                          ArrayList<HashMap<String, Object>> itemSubList =
                              (ArrayList<HashMap<String, Object>>)
                                  actions.get(row).get(Constants.KEY_ITEM_SUB);
                          if (itemSubTypeCode.equals("01")) {
                            String sourceId = util.null2string(
                                itemSubList.get(tag).get(Constants.KEY_SOURCE_ID));
                            String sourceSubId = util.null2string(
                                itemSubList.get(tag).get(Constants.KEY_SOURCE_SUB_ID));
                            String availableYn = util.null2string(
                                itemSubList.get(tag).get(Constants.KEY_AVAILABLE_YN));

                            if (availableYn.equals("N")) {
                              util.setShowToast(act, util.getString(act, R.string.MSG900),
                                  Toast.LENGTH_SHORT);
                              return;
                            } else {
                              intent = new Intent(act, RulesThingsSelect.class);
                              intent.putExtra(Constants.EXTRA_CALL_TYPE, "2");
                              intent.putExtra(Constants.EXTRA_TRIGGERS, triggers);
                              intent.putExtra(Constants.EXTRA_ACTIONS, actions);
                              intent.putExtra(Constants.EXTRA_CONDITIONS, conditions);
                              intent.putExtra(Constants.EXTRA_DEVICE_ID, sourceId);
                              intent.putExtra(Constants.EXTRA_NODE_ID, sourceSubId);
                              intent.putExtra(Constants.EXTRA_POSITION, tag);

                              util.callActivityForResultNoAnim(act, intent,
                                  Constants.ACT_RULES_THINGS_SELECT);
                            }
                            break;
                          }
                        }
                      }
                    }
                  });

              util.getView(childView, R.id.btnRowDelete).setTag(row1);
              util.getView(childView, R.id.btnRowDelete)
                  .setOnClickListener(new View.OnClickListener() {
                    int tag = 0;

                    @Override
                    public void onClick(View view) {

                      tag = (int) view.getTag();
                      for (int row = 0; row < actions.size(); row++) {
                        String itemSubTypeCode = util.null2string(
                            actions.get(row).get(Constants.KEY_ITEM_SUB_TYPE_CODE));
                        ArrayList<HashMap<String, Object>> itemSubList;
                        if (!util.null2string(
                            actions.get(row).get(Constants.KEY_ITEM_SUB)).equals("")) {
                          itemSubList = (ArrayList<HashMap<String, Object>>)
                              actions.get(row).get(Constants.KEY_ITEM_SUB);
                          if (itemSubTypeCode.equals("01")) {
                            itemSubList.remove(tag);
                            if (itemSubList.size() == 0) {
                              actions.remove(row);
                            }
                            break;
                          }
                        }
                      }
                      if (actions.size() <= 0) {
                        isRuleDeleteAll = true;
                      }
                      setDispActions();
                    }
                  });
              String sourceName = util.null2string(
                  itemSubList.get(row1).get(Constants.KEY_SOURCE_NAME));
              String availableYn = util.null2string(
                  itemSubList.get(row1).get(Constants.KEY_AVAILABLE_YN));
              if (availableYn.equals("N")) {
                util.getTextView(childView, R.id.tvRowTitle)
                    .setText(util.setSpCenterLine(act, sourceName));
              } else {
                util.getTextView(childView, R.id.tvRowTitle).setText(sourceName);
              }
              String sourceSubName = util.null2string(
                  itemSubList.get(row1).get(Constants.KEY_SOURCE_SUB_NAME));
              util.getTextView(childView, R.id.tvRowBody).setText(sourceSubName);
              util.getTextView(childView, R.id.tvRowState).setVisibility(View.VISIBLE);
              String conditionTypeCode = util.null2string(
                  itemSubList.get(row1).get(Constants.KEY_CONDITION_TYPE_CODE));
              String conditionTypeCodeName = util.null2string(
                  itemSubList.get(row1).get(Constants.KEY_CONDITION_TYPE_CODE_NAME));
              String cmdclsValue = util.null2string(
                  itemSubList.get(row1).get(Constants.KEY_CMDCLS_VALUE));
              String cmdclsValueMsg = util.null2string(
                  itemSubList.get(row1).get(Constants.KEY_CMDCLS_VALUE_MSG));
              String unit = util.null2string(
                  itemSubList.get(row1).get(Constants.KEY_UNIT));
              util.getTextView(childView, R.id.tvRowState)
                  .setText((cmdclsValueMsg.equals("") ? cmdclsValue : cmdclsValueMsg) + unit + (
                  conditionTypeCode.equals("01")
                      ? ""
                      : conditionTypeCodeName));
              String imageFileName = util.null2string(
                  itemSubList.get(row1).get(Constants.KEY_IMAGE_FILE_NAME));
              util.setImage(act, imageFileName, util.getImageView(childView, R.id.ivRowIcon));
              util.getLinearLayout(act, R.id.llActionBody).addView(childView);
            }
          }
        }
      }
    }
  }
}
