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

package com.ntels.kneet.v3.view.rules;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
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.kneet.v3.R;
import com.ntels.kneet.v3.common.AppConfig;
import com.ntels.kneet.v3.common.Constants;
import com.ntels.kneet.v3.common.c_interface.Main_Interface;
import com.ntels.kneet.v3.common.util.Util;
import com.ntels.kneet.v3.common.widget.CustomActivity;
import com.ntels.kneet.v3.view.dialog.CustomDialog;

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

public class Rules_Temperature_Select extends CustomActivity implements View.OnClickListener,
                                                                        CustomDialog.OnMsgAlterToResult {

    /** Called when the activity is first created. */

    private Toolbar   toolbar;
    private AppConfig appConfig;
    Main_Interface mCallback;
    private Util util = new Util();
    private Intent   intent;
    private Activity act;
    //    private DecimalFormat decimalFormat = new DecimalFormat("00");

    private CustomDialog                       customDialog      = new CustomDialog();
    private String                             sCallType         = "";
    private String                             sTemperature      = "";
    private ArrayList<HashMap<String, Object>> alList_Triggers   = new ArrayList<HashMap<String, Object>>();
    private ArrayList<HashMap<String, Object>> alList_Conditions = new ArrayList<HashMap<String, Object>>();
    private HashMap<String, Object>            hmItem_Sub        = new HashMap<String, Object>();
    private Button btnUpTemperature, btnDownTemperature;
    private TextView tvUpTemperature;
    private TextView tvDownTemperature;
    private EditText edtTemperature;
    private int iEdtMaxLength     = 0;
    private int iTemperatureStart = -50;
    private int iTemperatureEnd   = 50;
    private int iTemperatureDefault   = 0;

    @Override public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        act = Rules_Temperature_Select.this;
        appConfig = (AppConfig) act.getApplicationContext();
        customDialog.setOnMsgAlterToResultEvent(this);

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

        this.setContentView(viewToLoad);
        String sTempHour = "";
        if ( savedInstanceState != null ) {

        } else {
            Intent intent = getIntent();
            sTemperature = intent.getStringExtra(Constants.EXTRA_TEMPERATURE);
        }

        displayListView();
    }

    private void displayListView() {

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

        setKeyDisp();

        iEdtMaxLength = util.null2string(iTemperatureStart + "").length() > util.null2string(iTemperatureEnd + "").length()
                        ? util.null2string(iTemperatureStart + "").length()
                        : util.null2string(iTemperatureEnd + "").length();
        edtTemperature.setFilters(new InputFilter[]{new InputFilter.LengthFilter(iEdtMaxLength)});

        if ( sTemperature.equals("") ) {
            edtTemperature.setText(iTemperatureDefault + "");
        } else {
            edtTemperature.setText(sTemperature);
        }
    }

    void setKeyDisp() {

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

                if ( actionId == EditorInfo.IME_ACTION_DONE ) {
                    edtTemperature.clearFocus();
                    InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
                return false;
            }
        });
        edtTemperature.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            public void onFocusChange(View v, 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 s, int start, int before, int count) {

            }

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

            }

            @Override public void afterTextChanged(Editable s) {
                try {
                    if ( util.null2int(s.toString()) > iTemperatureEnd ) {
                        edtTemperature.setText(iTemperatureEnd + "");
                        edtTemperature.selectAll();
                    } else if ( util.null2string(s.toString()).equals("") ) {
                        edtTemperature.setText(iTemperatureStart + "");
                        edtTemperature.selectAll();
                    } else {
                        int iCurentTemperature = util.null2int(s.toString());
                        if ( iCurentTemperature > iTemperatureStart ) {
                            tvUpTemperature.setText((iCurentTemperature - 1) + "");
                            if ( iCurentTemperature < iTemperatureEnd ) {
                                tvDownTemperature.setText((iCurentTemperature + 1) + "");
                            } else {
                                tvDownTemperature.setText(iTemperatureStart + "");
                            }
                        } else {
                            tvUpTemperature.setText(iTemperatureEnd + "");
                            tvDownTemperature.setText((iTemperatureStart + 1) + "");
                        }

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

    @Override public void onClick(View v) {

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

    @Override public void resultCustomDialogResponse(int iMsgID, int iBtnResult) {

        switch (iMsgID) {

            case Constants.MSG998:
                util.callApp_Start(act, "LOGOUT");
                break;
            case Constants.MSG997:
                util.callApp_Start(act, "HOME_RELOAD");
                break;
            case Constants.MSG805:
                if ( iBtnResult == 1 ) {
                    // ComHandler.sendMessage(ComHandler.obtainMessage(MSG_COM_DOLOGOUT));
                }
                break;
            default:
                break;
        }
    }

    @Override protected void onSaveInstanceState(Bundle outState) {

        super.onSaveInstanceState(outState);
    }

    @Override public void onBackPressed() {

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