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

package com.ntels.onecable.view.rules;

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

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

  private static final int MSG_COM_G_COMMON_WEATHER_LOCATION_CODES = 1;

  private Util util = new Util();
  private Intent intent;
  private Activity act;

  private String dayOfWeek = "";
  private ArrayList<HashMap<String, Object>> triggers = new ArrayList<>();
  private ArrayList<HashMap<String, Object>> conditions = new ArrayList<>();
  private HashMap<String, Object> itemSubMap = new HashMap<>();

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

  private CustomDialog customDialog = new CustomDialog();
  private int areaPosition = -1;
  private String area = "";
  private String areaCode = "";
  private ArrayList<String> alAreaTitle = new ArrayList<>();
  private ArrayList<String> alAreaId = new ArrayList<>();

  @SuppressWarnings("unchecked")
  @Override
  public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

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

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

    this.setContentView(viewToLoad);
    if (null != getIntent()) {
      Intent intent = getIntent();

      triggers = (ArrayList<HashMap<String, Object>>)
          intent.getSerializableExtra(Constants.EXTRA_TRIGGERS);
      conditions = (ArrayList<HashMap<String, Object>>)
          intent.getSerializableExtra(Constants.EXTRA_CONDITIONS);
    }

    displayListView();
  }

  /**
   * 일출/일몰 trigger 가져오기.
   */
  @SuppressWarnings("unchecked")
  void getTriggersSun() {

    if (triggers.size() > 0) {
      int row = 0;
      int row1 = 0;
      String itemSubTypeCode = util.null2string(
          triggers.get(row).get(Constants.KEY_ITEM_SUB_TYPE_CODE));
      ArrayList<HashMap<String, Object>> itemSubList;
      if (!util.null2string(triggers.get(row).get(Constants.KEY_ITEM_SUB)).equals("")) {
        itemSubList = (ArrayList<HashMap<String, Object>>)
            triggers.get(row).get(Constants.KEY_ITEM_SUB);
        if (itemSubTypeCode.equals("32")) {
          itemSubMap = itemSubList.get(row1);

          String sourceSubId = util.null2string(itemSubMap.get(Constants.KEY_SOURCE_SUB_ID));
          Dlog.v("sunriseUtcTime sourceSubId=" + sourceSubId);
          if (sourceSubId.equals("sunriseUtcTime")) {
            util.getView(act, R.id.btnSun1).setSelected(true);
            util.getView(act, R.id.btnSun2).setSelected(false);
          } else if (sourceSubId.equals("sunsetUtcTime")) {
            util.getView(act, R.id.btnSun1).setSelected(false);
            util.getView(act, R.id.btnSun2).setSelected(true);
          }
          areaCode = util.null2string(itemSubMap.get(Constants.KEY_SOURCE_ID));
          area = util.null2string(itemSubMap.get(Constants.KEY_SOURCE_NAME));
          util.getTextView(act, R.id.tvArea).setText(area);
          util.getViewUnderline(act, R.id.tvArea);
        }
      }
    }
  }

  /**
   * 요일 가져오기.
   */
  @SuppressWarnings("unchecked")
  void getDayOfWeek() {

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

        String itemSubTypeCode = util.null2string(tempMap.get(Constants.KEY_ITEM_SUB_TYPE_CODE));
        if (itemSubTypeCode.equals("22")) {
          //요일
          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 (itemSubList.size() > 0) {
              HashMap<String, Object> tempItemSubMap;
              tempItemSubMap = itemSubList.get(0);

              dayOfWeek = util.null2string(tempItemSubMap.get(Constants.KEY_CMDCLS_VALUE));
            }
          }

          util.getView(act, R.id.llMon).setSelected(false);
          util.getView(act, R.id.llTue).setSelected(false);
          util.getView(act, R.id.llWed).setSelected(false);
          util.getView(act, R.id.llThu).setSelected(false);
          util.getView(act, R.id.llFri).setSelected(false);
          util.getView(act, R.id.llSat).setSelected(false);
          util.getView(act, R.id.llSun).setSelected(false);
          if (!dayOfWeek.equals("")) {
            String[] strArray = dayOfWeek.split("\\,", 100);
            for (String s : strArray) {
              switch (s) {
                case "MON":
                  util.getView(act, R.id.llMon).setSelected(true);
                  break;
                case "TUE":
                  util.getView(act, R.id.llTue).setSelected(true);
                  break;
                case "WED":
                  util.getView(act, R.id.llWed).setSelected(true);
                  break;
                case "THU":
                  util.getView(act, R.id.llThu).setSelected(true);
                  break;
                case "FRI":
                  util.getView(act, R.id.llFri).setSelected(true);
                  break;
                case "SAT":
                  util.getView(act, R.id.llSat).setSelected(true);
                  break;
                case "SUN":
                  util.getView(act, R.id.llSun).setSelected(true);
                  break;
                default:
                  break;
              }
            }
          }
          break;
        }
      }
    }
  }

  /**
   * 요일 설정하기.
   *
   * @return 설정 여부
   */
  private Boolean setsDayOfWeek() {

    String tempDayOfWeek = "";
    if (util.getView(act, R.id.llMon).isSelected()) {
      if (!tempDayOfWeek.equals("")) {
        tempDayOfWeek = tempDayOfWeek + ",";
      }
      tempDayOfWeek = tempDayOfWeek + "MON";
    }
    if (util.getView(act, R.id.llTue).isSelected()) {
      if (!tempDayOfWeek.equals("")) {
        tempDayOfWeek = tempDayOfWeek + ",";
      }
      tempDayOfWeek = tempDayOfWeek + "TUE";
    }
    if (util.getView(act, R.id.llWed).isSelected()) {
      if (!tempDayOfWeek.equals("")) {
        tempDayOfWeek = tempDayOfWeek + ",";
      }
      tempDayOfWeek = tempDayOfWeek + "WED";
    }
    if (util.getView(act, R.id.llThu).isSelected()) {
      if (!tempDayOfWeek.equals("")) {
        tempDayOfWeek = tempDayOfWeek + ",";
      }
      tempDayOfWeek = tempDayOfWeek + "THU";
    }
    if (util.getView(act, R.id.llFri).isSelected()) {
      if (!tempDayOfWeek.equals("")) {
        tempDayOfWeek = tempDayOfWeek + ",";
      }
      tempDayOfWeek = tempDayOfWeek + "FRI";
    }
    if (util.getView(act, R.id.llSat).isSelected()) {
      if (!tempDayOfWeek.equals("")) {
        tempDayOfWeek = tempDayOfWeek + ",";
      }
      tempDayOfWeek = tempDayOfWeek + "SAT";
    }
    if (util.getView(act, R.id.llSun).isSelected()) {
      if (!tempDayOfWeek.equals("")) {
        tempDayOfWeek = tempDayOfWeek + ",";
      }
      tempDayOfWeek = tempDayOfWeek + "SUN";
    }
    if (tempDayOfWeek.equals("")) {
      customDialog.msgAlert(act, Constants.MSG855);
      return false;
    }

    String[] alItem = util.getStringArrayValues(act, "DAYOFWEEK_ITEM");
    String[] alText = util.getStringArrayValues(act, "DAYOFWEEK_TEXT");
    String tempDayOfWeek1 = tempDayOfWeek;
    String[] strArray = tempDayOfWeek.split("\\,", 100);
    for (String s : strArray) {
      int idx = util.getArraryFind(alItem, s);
      tempDayOfWeek1 = tempDayOfWeek1.replaceAll(s, alText[idx]);
    }

    HashMap<String, Object> tempItemSubMap = new HashMap<String, Object>();

    String tempSourceId = "";
    tempItemSubMap.put(Constants.KEY_SOURCE_ID, tempSourceId);
    String tempSourceSubId = "";
    tempItemSubMap.put(Constants.KEY_SOURCE_SUB_ID, tempSourceSubId);
    String tempConditionTypeCode = "09";
    tempItemSubMap.put(Constants.KEY_CONDITION_TYPE_CODE, tempConditionTypeCode);
    String tempCmdclsValue = tempDayOfWeek;
    tempItemSubMap.put(Constants.KEY_CMDCLS_VALUE, tempCmdclsValue);
    String tempCmdclsValueMsg = tempDayOfWeek1;
    tempItemSubMap.put(Constants.KEY_CMDCLS_VALUE_MSG, tempCmdclsValueMsg);

    ArrayList<HashMap<String, Object>> tempItemSubList = new ArrayList<HashMap<String, Object>>();
    tempItemSubList.add(tempItemSubMap);

    HashMap<String, Object> hmTempCondition = new HashMap<String, Object>();
    hmTempCondition.put(Constants.KEY_ITEM_NAME, "");
    hmTempCondition.put(Constants.KEY_ITEM_SUB_TYPE_CODE, "22");
    hmTempCondition.put(Constants.KEY_ITEM_SUB, tempItemSubList);

    boolean isSet = false;
    if (conditions.size() > 0) {
      for (int row = 0; row < conditions.size(); row++) {
        HashMap<String, Object> hmTemp;
        hmTemp = conditions.get(row);

        String itemSubTypeCode = util.null2string(hmTemp.get(Constants.KEY_ITEM_SUB_TYPE_CODE));
        if (itemSubTypeCode.equals("22")) {
          conditions.set(row, hmTempCondition);
          isSet = true;
          break;
        }
      }

      if (!isSet) {
        conditions.add(hmTempCondition);
      }
    } else {
      conditions.add(hmTempCondition);
    }

    return true;
  }


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

    util.getTextView(act, R.id.tvArea).setText(util.getString(act, R.string.layout_selected));
    util.getViewUnderline(act, R.id.tvArea);
    util.getView(act, R.id.btnSun1).setSelected(true);
    util.getView(act, R.id.btnSun2).setSelected(false);
    util.getView(act, R.id.tvArea).setOnClickListener(this);
    util.getView(act, R.id.btnSun1).setOnClickListener(this);
    util.getView(act, R.id.btnSun2).setOnClickListener(this);
    util.getView(act, R.id.llMon).setOnClickListener(this);
    util.getView(act, R.id.llTue).setOnClickListener(this);
    util.getView(act, R.id.llWed).setOnClickListener(this);
    util.getView(act, R.id.llThu).setOnClickListener(this);
    util.getView(act, R.id.llFri).setOnClickListener(this);
    util.getView(act, R.id.llSat).setOnClickListener(this);
    util.getView(act, R.id.llSun).setOnClickListener(this);
    util.getView(act, R.id.llBtn1).setOnClickListener(this);
    util.getView(act, R.id.llBtn2).setOnClickListener(this);
    util.getView(act, R.id.llMon).setSelected(true);
    util.getView(act, R.id.llTue).setSelected(true);
    util.getView(act, R.id.llWed).setSelected(true);
    util.getView(act, R.id.llThu).setSelected(true);
    util.getView(act, R.id.llFri).setSelected(true);
    util.getView(act, R.id.llSat).setSelected(true);
    util.getView(act, R.id.llSun).setSelected(true);

    getTriggersSun();

    getDayOfWeek();


    comHandler.sendMessageDelayed(comHandler.obtainMessage(
        MSG_COM_G_COMMON_WEATHER_LOCATION_CODES), 10);
  }

  @Override
  public void onClick(View view) {

    switch (view.getId()) {
      case R.id.llBtn1:
        if (areaPosition == -1) {
          customDialog.msgAlert(act, Constants.MSG860);
          return;
        }
        if (setsDayOfWeek()) {
          String sourceId = "";
          String sourceName = "";
          if (areaPosition > -1) {
            sourceId = util.null2string(alAreaId.get(areaPosition));
            sourceName = util.null2string(alAreaTitle.get(areaPosition));
          } else {
            customDialog.msgAlert(act, Constants.MSG860);
            return;
          }
          String sourceSubId = "";
          String sourceSubName = "";
          if (util.getView(act, R.id.btnSun1).isSelected()) {
            sourceSubId = "sunriseUtcTime";
            sourceSubName = util.getString(act, R.string.layout_rules_triggers_sun_02);
          } else {
            sourceSubId = "sunsetUtcTime";
            sourceSubName = util.getString(act, R.string.layout_rules_triggers_sun_03);
          }

          itemSubMap.put(Constants.KEY_SOURCE_ID, sourceId);
          itemSubMap.put(Constants.KEY_SOURCE_NAME, sourceName);
          itemSubMap.put(Constants.KEY_SOURCE_SUB_ID, sourceSubId);
          itemSubMap.put(Constants.KEY_SOURCE_SUB_NAME, sourceSubName);
          String conditionTypeCode = "";
          itemSubMap.put(Constants.KEY_CONDITION_TYPE_CODE, conditionTypeCode);
          String cmdclsValue = "";
          itemSubMap.put(Constants.KEY_CMDCLS_VALUE, cmdclsValue);
          String dataTypeCode = "";
          itemSubMap.put(Constants.KEY_DATA_TYPE_CODE, dataTypeCode);
          String dayOfWeek = "";
          itemSubMap.put(Constants.KEY_DAYOFWEEK, dayOfWeek);
          String repeatable = "";
          itemSubMap.put(Constants.KEY_REPEATABLE, repeatable);
          String hour = "";
          itemSubMap.put(Constants.KEY_HOUR, hour);
          String minute = "";
          itemSubMap.put(Constants.KEY_MINUTE, minute);

          ArrayList<HashMap<String, Object>> itemSubList = new ArrayList<>();
          itemSubList.clear();
          itemSubList.add(itemSubMap);

          triggers.clear();

          HashMap<String, Object> hmTriggers = new HashMap<String, Object>();
          hmTriggers.put(Constants.KEY_ITEM_SUB, itemSubList);
          hmTriggers.put(Constants.KEY_ITEM_NAME,
              util.getString(act, R.string.layout_rules_triggers_select_03));
          hmTriggers.put(Constants.KEY_ITEM_SUB_TYPE_CODE, "32");

          triggers.add(hmTriggers);

          intent = new Intent();
          intent.putExtra(Constants.EXTRA_TRIGGERS, triggers);
          intent.putExtra(Constants.EXTRA_CONDITIONS, conditions);
          act.setResult(RESULT_OK, intent);
          finish();
        }
        break;
      case R.id.llBtn2:
        onBackPressed();
        break;
      case R.id.btnSun1:
        util.getView(act, R.id.btnSun1).setSelected(true);
        util.getView(act, R.id.btnSun2).setSelected(false);
        break;
      case R.id.btnSun2:
        util.getView(act, R.id.btnSun1).setSelected(false);
        util.getView(act, R.id.btnSun2).setSelected(true);
        break;
      case R.id.tvArea:
        intent = new Intent();
        intent.setClass(act, DialogSpinner.class);
        intent.putExtra(Constants.EXTRA_SPINNER_LIST1, alAreaTitle);
        intent.putExtra(Constants.EXTRA_SPINNER_TITLE,
            util.getString(act, R.string.layout_rules_location_select_01));
        intent.putExtra(Constants.EXTRA_SPINNER_TYPE, 0);
        intent.putExtra(Constants.EXTRA_SPINNER_POSITION, areaPosition);
        util.callActivityForResultNoAnim(act, intent, Constants.ACT_SPINNER);
        break;
      case R.id.llMon:
      case R.id.llTue:
      case R.id.llWed:
      case R.id.llThu:
      case R.id.llFri:
      case R.id.llSat:
      case R.id.llSun:
        if (view.isSelected()) {
          view.setSelected(false);
        } else {
          view.setSelected(true);
        }
        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_G_COMMON_WEATHER_LOCATION_CODES:
          sendGetCommonWeatherLocationCodes();
          break;

        default:
          break;
      }
      return true;
    }
  }

  /**
   * 야후날씨 지역코드 목록 조회(야후 날씨에 사용할 지역코드목록을 조회한다) 요청.
   */
  private void sendGetCommonWeatherLocationCodes() {

    try {
      HttpSend httpSend;

      httpSend = new HttpSend(act);

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

          resultGetCommonWeatherLocationCodes(result);
        }
      });
      httpSend.G_common_weather_location_codes();
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }

  /**
   * {@link RulesTriggersSun#sendGetCommonWeatherLocationCodes() 지역코드} 요청 결과.
   *
   * @param response 결과 data
   */
  private void resultGetCommonWeatherLocationCodes(Response response) {

    try {
      if (response.getStatusCode() == 200) {
        ArrayList<HashMap<String, Object>> alList = util.jsonToArrayListMap(response.getContent());
        if (alList.size() > 0) {
          for (int row = 0; row < alList.size(); row++) {
            HashMap<String, Object> hmTemp;
            hmTemp = alList.get(row);
            String commonCode = util.null2string(hmTemp.get(Constants.KEY_COMMON_CODE));
            String commonCodeName = util.null2string(hmTemp.get(Constants.KEY_COMMON_CODE_NAME));
            alAreaId.add(commonCode);
            alAreaTitle.add(commonCodeName);
            if (commonCode.equals(areaCode)) {
              areaPosition = row;
              String area = util.null2string(alAreaTitle.get(areaPosition));
              util.getTextView(act, R.id.tvArea).setText(area);
              util.getViewUnderline(act, R.id.tvArea);
            }
          }
        }
      } 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 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.MSG805:
        if (btnResult == 1) {
          // comHandler.sendMessage(comHandler.obtainMessage(MSG_COM_DOLOGOUT));
        }
        break;

      default:
        break;
    }
  }

  @Override
  public void onBackPressed() {

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

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

    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {
      switch (requestCode) {
        case Constants.ACT_SPINNER:
          if (areaPosition != data.getIntExtra(Constants.EXTRA_SPINNER_RESULT, 0)) {
            areaPosition = data.getIntExtra(Constants.EXTRA_SPINNER_RESULT, 0);
            area = util.null2string(alAreaTitle.get(areaPosition));
            util.getTextView(act, R.id.tvArea).setText(area);
            util.getViewUnderline(act, R.id.tvArea);
          }
          break;
        default:
          break;
      }
    } else {
      switch (requestCode) {
        default:
          break;
      }
    }
  }
}
