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

package com.ntels.onecable.view.rules;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.ntels.onecable.R;
import com.ntels.onecable.common.Constants;
import com.ntels.onecable.common.util.Dlog;
import com.ntels.onecable.common.util.Util;
import com.ntels.onecable.common.widget.CustomActivity;

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

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

  private String multiSensorName = "";
  private String multiSensor = "";
  private String multiSensorConditionTypeCode = "";
  private String multiSensorUnit = "";
  private TextView tvUpMultiSensor;
  private TextView tvDownMultiSensor;
  private EditText edtMultiSensor;
  private int edtMaxLength = 0;
  private int multiSensorStep = 1;
  private int multiSensorStart = 0;
  private int multiSensorEnd = 99;
  private String mItemTypeCode;

  @Override
  public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    act = RulesMultiSensorSelect.this;

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

    if (null != getIntent()) {
      Intent intent = getIntent();
      multiSensorName = util.null2string(intent.getStringExtra(Constants.EXTRA_NAME));
      multiSensorUnit = util.null2string(intent.getStringExtra(Constants.EXTRA_UNIT));
      multiSensorStart = intent.getIntExtra(Constants.EXTRA_MIN, multiSensorStart);
      multiSensorEnd = intent.getIntExtra(Constants.EXTRA_MAX, multiSensorEnd);
      multiSensorStep = intent.getIntExtra(Constants.EXTRA_STEP, multiSensorStep);
      multiSensorConditionTypeCode = util.null2string(
          intent.getStringExtra(Constants.EXTRA_CONDITION_TYPE_CODE));
      multiSensor = util.null2string(intent.getStringExtra(Constants.EXTRA_MULTISENSOR));
      mItemTypeCode = util.null2string(intent.getStringExtra(Constants.EXTRA_ITEM_TYPE_CODE));
    }

    displayListView();
  }

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

    util.getView(act, R.id.llRowCheck1).setOnClickListener(this);
    util.getView(act, R.id.llRowCheck2).setOnClickListener(this);
    util.getView(act, R.id.llBtn1).setOnClickListener(this);
    util.getView(act, R.id.llBtn2).setOnClickListener(this);
    tvUpMultiSensor = (TextView) findViewById(R.id.tvUpMultisensor);
    edtMultiSensor = (EditText) findViewById(R.id.edtMultisensor);
    tvDownMultiSensor = (TextView) findViewById(R.id.tvDownMultisensor);
    Button btnUpMultiSensor = (Button) findViewById(R.id.btnUpMultisensor);
    btnUpMultiSensor.setOnClickListener(this);
    tvUpMultiSensor.setOnClickListener(this);
    tvDownMultiSensor.setOnClickListener(this);
    Button btnDownMultiSensor = (Button) findViewById(R.id.btnDownMultisensor);
    btnDownMultiSensor.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(multiSensorName);

    setKeyDisp();

    edtMaxLength = util.null2string(multiSensorStart + "")
        .length() > util.null2string(multiSensorEnd + "").length()
        ? util.null2string(multiSensorStart + "").length()
        : util.null2string(multiSensorEnd + "").length();
    edtMultiSensor.setFilters(new InputFilter[]{new InputFilter.LengthFilter(edtMaxLength)});

    util.getTextView(act, R.id.tvUnit).setText(multiSensorUnit);
    if (multiSensor.equals("")) {
      edtMultiSensor.setText(String.valueOf(multiSensorStart));
    } else {
      edtMultiSensor.setText(multiSensor);
    }
    Dlog.v("multiSensorConditionTypeCode = ", multiSensorConditionTypeCode);
    if (!"02".equals(mItemTypeCode)) {
      if (multiSensorConditionTypeCode.equals("03")) {
        util.getView(act, R.id.llRowCheck1).setSelected(false);
        util.getView(act, R.id.llRowCheck2).setSelected(true);
      } else if (multiSensorConditionTypeCode.equals("05")) {
        util.getView(act, R.id.llRowCheck1).setSelected(true);
        util.getView(act, R.id.llRowCheck2).setSelected(false);
      }
    } else {
      util.getView(act, R.id.row_check_layout).setVisibility(View.GONE);
    }
  }

  /**
   * 키보드 설정.
   */
  void setKeyDisp() {

    edtMultiSensor.setImeOptions(EditorInfo.IME_ACTION_DONE); // 키보드 확인 버튼 클릭시
    edtMultiSensor.setOnEditorActionListener(new TextView.OnEditorActionListener() {
      @Override
      public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {

        if (actionId == EditorInfo.IME_ACTION_DONE) {
          edtMultiSensor.clearFocus();
          InputMethodManager imm = (InputMethodManager) view.getContext()
              .getSystemService(Context.INPUT_METHOD_SERVICE);
          imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
        return false;
      }
    });
    edtMultiSensor.setOnFocusChangeListener(new View.OnFocusChangeListener() {
      public void onFocusChange(View view, boolean hasFocus) {

        if (!hasFocus) {
          if (util.null2string(Math.abs(util.null2int(edtMultiSensor.getText()))).length() == 1) {
            edtMultiSensor.setText(edtMultiSensor.getText());
          }
        }
      }
    });
    edtMultiSensor.addTextChangedListener(new TextWatcher() {

      @Override
      public void onTextChanged(CharSequence chars, int start, int before, int count) {

      }

      @Override
      public void beforeTextChanged(CharSequence chars, int start, int count, int after) {

      }

      @Override
      public void afterTextChanged(Editable editable) {

        try {
          if (util.null2int(editable.toString()) > multiSensorEnd) {
            edtMultiSensor.setText(String.valueOf(multiSensorEnd));
            edtMultiSensor.selectAll();
          } else if (util.null2string(editable.toString()).equals("")) {
            edtMultiSensor.setText(String.valueOf(multiSensorStart));
            edtMultiSensor.selectAll();
          } else {
            int currentMultiSensor = util.null2int(editable.toString());
            if (currentMultiSensor > multiSensorStart) {
              tvUpMultiSensor.setText(String.valueOf(currentMultiSensor - multiSensorStep));
              if (currentMultiSensor < multiSensorEnd) {
                tvDownMultiSensor.setText(String.valueOf(currentMultiSensor + multiSensorStep));
              } else {
                tvDownMultiSensor.setText(String.valueOf(multiSensorStart));
              }
            } else {
              tvUpMultiSensor.setText(String.valueOf(multiSensorEnd));
              tvDownMultiSensor.setText(String.valueOf(multiSensorStart + multiSensorStep));
            }

            if (util.null2string(Math.abs(util.null2int(edtMultiSensor.getText()))).length()
                == edtMaxLength) {
              edtMultiSensor.selectAll();
            }
          }
        } catch (Exception ex) {
          ex.printStackTrace();
        }
      }
    });
  }

  @Override
  public void onClick(View view) {

    int currentMultiSensor = util.null2int(edtMultiSensor.getText());
    switch (view.getId()) {
      case R.id.llBtn1:
        intent = new Intent();
        intent.putExtra(Constants.EXTRA_MULTISENSOR, currentMultiSensor + "");
        String conditionTypeCode = "";
        if (!"02".equals(mItemTypeCode)) {
          if (util.getView(act, R.id.llRowCheck1).isSelected()) {
            conditionTypeCode = "05";
          } else if (util.getView(act, R.id.llRowCheck2).isSelected()) {
            conditionTypeCode = "03";
          } else {
            util.setShowToast(act, util.getString(act, R.string.MSG850), Toast.LENGTH_SHORT);
            return;
          }
        }
        intent.putExtra(Constants.EXTRA_CONDITION_TYPE_CODE, conditionTypeCode);
        intent.putExtra(Constants.EXTRA_UNIT, multiSensorUnit);
        intent.putExtra(Constants.EXTRA_ITEM_TYPE_CODE, mItemTypeCode);
        act.setResult(RESULT_OK, intent);
        finish();
        break;
      case R.id.llBtn2:
        onBackPressed();
        break;
      case R.id.llRowCheck1:
        util.getView(act, R.id.llRowCheck1).setSelected(true);
        util.getView(act, R.id.llRowCheck2).setSelected(false);
        break;
      case R.id.llRowCheck2:
        util.getView(act, R.id.llRowCheck1).setSelected(false);
        util.getView(act, R.id.llRowCheck2).setSelected(true);
        break;
      case R.id.btnUpMultisensor:
      case R.id.tvUpMultisensor:
        if (currentMultiSensor > multiSensorStart) {
          currentMultiSensor -= multiSensorStep;
          edtMultiSensor.setText(String.valueOf(currentMultiSensor));
          edtMultiSensor.selectAll();
        } else {
          currentMultiSensor = multiSensorEnd;
          edtMultiSensor.setText(String.valueOf(currentMultiSensor));
          edtMultiSensor.selectAll();
        }
        break;
      case R.id.tvDownMultisensor:
      case R.id.btnDownMultisensor:
        if (currentMultiSensor < multiSensorEnd) {
          currentMultiSensor += multiSensorStep;
          edtMultiSensor.setText(String.valueOf(currentMultiSensor));
          edtMultiSensor.selectAll();
        } else {
          currentMultiSensor = multiSensorStart;
          edtMultiSensor.setText(String.valueOf(currentMultiSensor));
          edtMultiSensor.selectAll();
        }
        break;
      default:
        break;
    }
  }

  @Override
  public void onBackPressed() {

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