/*
 * 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 com.ntels.onecable.R;
import com.ntels.onecable.common.Constants;
import com.ntels.onecable.common.util.Util;
import com.ntels.onecable.common.widget.CustomActivity;

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

  private Util util = new Util();
  private Intent intent;
  private Activity act;
  private String temperature = "";
  private TextView tvUpTemperature;
  private TextView tvDownTemperature;
  private EditText edtTemperature;
  private int edtMaxLength = 0;
  private int temperatureStart = -50;
  private int temperatureEnd = 50;

  @Override
  public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    act = RulesTemperatureSelect.this;

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

    this.setContentView(viewToLoad);
    if (null != getIntent()) {
      Intent intent = getIntent();
      temperature = intent.getStringExtra(Constants.EXTRA_TEMPERATURE);
    }

    displayListView();
  }

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

    util.getView(act, R.id.llBtn1).setOnClickListener(this);
    util.getView(act, R.id.llBtn2).setOnClickListener(this);
    tvUpTemperature = (TextView) findViewById(R.id.tvUpTemperature);
    edtTemperature = (EditText) findViewById(R.id.edtTemperature);
    tvDownTemperature = (TextView) findViewById(R.id.tvDownTemperature);
    Button btnUpTemperature = (Button) findViewById(R.id.btnUpTemperature);
    btnUpTemperature.setOnClickListener(this);
    tvUpTemperature.setOnClickListener(this);
    tvDownTemperature.setOnClickListener(this);
    Button btnDownTemperature = (Button) findViewById(R.id.btnDownTemperature);
    btnDownTemperature.setOnClickListener(this);

    setKeyDisp();

    edtMaxLength = util.null2string(temperatureStart + "").length()
        > util.null2string(temperatureEnd + "").length()
        ? util.null2string(temperatureStart + "").length()
        : util.null2string(temperatureEnd + "").length();
    edtTemperature.setFilters(new InputFilter[]{new InputFilter.LengthFilter(edtMaxLength)});

    if (temperature.equals("")) {
      int temperatureDefault = 0;
      edtTemperature.setText(String.valueOf(temperatureDefault));
    } else {
      edtTemperature.setText(temperature);
    }
  }

  void setKeyDisp() {

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

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

        if (!hasFocus) {
          if (util.null2string(Math.abs(util.null2int(edtTemperature.getText()))).length() == 1) {
            edtTemperature.setText(edtTemperature.getText());
          }
        }
      }
    });
    edtTemperature.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()) > temperatureEnd) {
            edtTemperature.setText(String.valueOf(temperatureEnd));
            edtTemperature.selectAll();
          } else if (util.null2string(editable.toString()).equals("")) {
            edtTemperature.setText(String.valueOf(temperatureStart));
            edtTemperature.selectAll();
          } else {
            int currentTemperature = util.null2int(editable.toString());
            if (currentTemperature > temperatureStart) {
              tvUpTemperature.setText(String.valueOf(currentTemperature - 1));
              if (currentTemperature < temperatureEnd) {
                tvDownTemperature.setText(String.valueOf(currentTemperature + 1));
              } else {
                tvDownTemperature.setText(String.valueOf(temperatureStart));
              }
            } else {
              tvUpTemperature.setText(String.valueOf(temperatureEnd));
              tvDownTemperature.setText(String.valueOf(temperatureStart + 1));
            }

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

  @Override
  public void onClick(View view) {

    int currentTemperature = util.null2int(edtTemperature.getText());
    switch (view.getId()) {
      case R.id.llBtn1:
        intent = new Intent();
        intent.putExtra(Constants.EXTRA_TEMPERATURE, currentTemperature + "");
        act.setResult(RESULT_OK, intent);
        finish();
        break;
      case R.id.llBtn2:
        onBackPressed();
        break;
      case R.id.btnUpTemperature:
      case R.id.tvUpTemperature:
        if (currentTemperature > temperatureStart) {
          currentTemperature--;
          edtTemperature.setText(String.valueOf(currentTemperature));
          edtTemperature.selectAll();
        } else {
          currentTemperature = temperatureEnd;
          edtTemperature.setText(String.valueOf(currentTemperature));
          edtTemperature.selectAll();
        }
        break;
      case R.id.tvDownTemperature:
      case R.id.btnDownTemperature:
        if (currentTemperature < temperatureEnd) {
          currentTemperature++;
          edtTemperature.setText(String.valueOf(currentTemperature));
          edtTemperature.selectAll();
        } else {
          currentTemperature = temperatureStart;
          edtTemperature.setText(String.valueOf(currentTemperature));
          edtTemperature.selectAll();
        }
        break;
      default:
        break;
    }
  }

  @Override
  public void onBackPressed() {

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