package kr.co.icontrols.ilp300_700.admin.setting;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.widget.RelativeLayout;

import kr.co.icontrols.ilp300_700.MainActivity;
import kr.co.icontrols.ilp300_700.R;
import kr.co.icontrols.ilp300_700.ethernet.iMAPCommon.iMAPResult;
import kr.co.icontrols.ilp300_700.global.Configure.ConfigValKey;
import kr.co.icontrols.ilp300_700.global.Configure.ConfigValue;
import kr.co.icontrols.ilp300_700.global.DataClasses.POSITION;
import kr.co.icontrols.ilp300_700.global.Declare;
import kr.co.icontrols.ilp300_700.global.Declare.MultiReaderPacket;
import kr.co.icontrols.ilp300_700.global.ID;
import kr.co.icontrols.ilp300_700.imap.iMAPResultCtrl;
import kr.co.icontrols.ilp300_700.rfmsg.Request_MultiRF_ZBSensitivity;
import kr.co.icontrols.wallpadsupport.WpadImageView;
import kr.co.icontrols.wallpadsupport.WpadScreen;
import kr.co.icontrols.wallpadsupport.WpadTextView;

public class AdminSet_Setting_ZigBeeSensitivity extends WpadScreen {

    String TAG = "AdminSet_Setting_ZigBeeSensitivity";

    boolean bLOG = true;   // true, false
    boolean bLOG_DEBUG = false;   // true, false
    boolean bLOG_INFO = true;   // true, false
    Context mContext;
    WpadImageView Image_Background;
    WpadTextView Text_Title;
    WpadTextView Text_Line_01_Item;
    WpadTextView Text_Line_02_Item;
    WpadTextView Text_Line_03_Item;
    int TextColor_Normal = Color.WHITE;
    int TextColor_Highlight = Color.GREEN;
    int TextColor_Fail = Color.RED;
    int TextColor_Wait = Color.YELLOW;
    int nFontSize_Menu = 28;
    int nFontSize_Instruction = 22;
    boolean bFontNonBold = false;
    boolean bFontBold = true;
    int nZigBee_Sensitivity = 0;
    int MIN_ZIGBEE_SENSITIVITY = -100;
    int MAX_ZIGBEE_SENSITIVITY = 100;
    String strInfoMent_GetResultFail = "카드리더기가 응답하지 않습니다.";
    String strInfoMent_PleaseWait = "잠시만 기다리세요.";
    String strText_Title = "ZigBee 신호 감도 조절";
    String strText_Line_01_Item = strInfoMent_PleaseWait;
    protected Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                LOG("[mHandler] strText_Line_01_Item [" + strText_Line_01_Item + "]");
                if (strText_Line_01_Item.equals(strInfoMent_GetResultFail))
                    Text_Line_01_Item.setTextColor(TextColor_Fail);
                else Text_Line_01_Item.setTextColor(TextColor_Highlight);

                Text_Line_01_Item.setText(strText_Line_01_Item);
            }
        }
    };
    String strText_Line_02_Item = "1: ↓-5                3: ↑5";
    String strText_Line_03_Item = "- 신호 감도 선택 후 '경비실'버튼을 누르세요. -";
    // X'7B ('01: READ)
    boolean bGet = false;
    public AdminSet_Setting_ZigBeeSensitivity(Context context, RelativeLayout layout) {
        super(context, layout);
        try {
            LOG("------------------ [START - AdminSet_Setting_ZigBeeSensitivity] -------------------");

            mContext = context;
            Initialize();

            Image_Background = new WpadImageView(context, 0, Declare.DeviceInfo.getScreenSizeFullW(ConfigValue.DEVICE_MODELTYPE), Declare.DeviceInfo.getScreenSizeFullH(ConfigValue.DEVICE_MODELTYPE), R.drawable.bg_back, 0, ID.SCREENS.ADMINSET_SETTING_ZIGBEESENSITIVITY.ELEMENTS.IMAGES.BACKGROUND);
            ViewRegistration(layout, Image_Background, 0, 0);

            Text_Title = new WpadTextView(context, false, getPosition(ID.SCREENS.ADMINSET_SETTING_ZIGBEESENSITIVITY.ELEMENTS.TEXTS.TITLE).W, getPosition(ID.SCREENS.ADMINSET_SETTING_ZIGBEESENSITIVITY.ELEMENTS.TEXTS.TITLE).H, Gravity.CENTER, Color.WHITE, nFontSize_Menu, bFontBold, ID.SCREENS.ADMINSET_SETTING_ZIGBEESENSITIVITY.ELEMENTS.TEXTS.TITLE);
            ViewRegistration(layout, Text_Title, getPosition(ID.SCREENS.ADMINSET_SETTING_ZIGBEESENSITIVITY.ELEMENTS.TEXTS.TITLE).X, getPosition(ID.SCREENS.ADMINSET_SETTING_ZIGBEESENSITIVITY.ELEMENTS.TEXTS.TITLE).Y);
            Text_Title.setText(strText_Title);

            Text_Line_01_Item = new WpadTextView(context, false, getPosition(ID.SCREENS.ADMINSET_SETTING_ZIGBEESENSITIVITY.ELEMENTS.TEXTS.LINE_01_ITEM).W, getPosition(ID.SCREENS.ADMINSET_SETTING_ZIGBEESENSITIVITY.ELEMENTS.TEXTS.LINE_01_ITEM).H, Gravity.CENTER, TextColor_Highlight, nFontSize_Menu, bFontNonBold, ID.SCREENS.ADMINSET_SETTING_ZIGBEESENSITIVITY.ELEMENTS.TEXTS.LINE_01_ITEM);
            ViewRegistration(layout, Text_Line_01_Item, getPosition(ID.SCREENS.ADMINSET_SETTING_ZIGBEESENSITIVITY.ELEMENTS.TEXTS.LINE_01_ITEM).X, getPosition(ID.SCREENS.ADMINSET_SETTING_ZIGBEESENSITIVITY.ELEMENTS.TEXTS.LINE_01_ITEM).Y);
            if (sendGetZigBeeSensitivity()) Text_Line_01_Item.setText(strText_Line_01_Item);
            else Text_Line_01_Item.setText(strInfoMent_GetResultFail);

            Text_Line_02_Item = new WpadTextView(context, false, getPosition(ID.SCREENS.ADMINSET_SETTING_ZIGBEESENSITIVITY.ELEMENTS.TEXTS.LINE_02_ITEM).W, getPosition(ID.SCREENS.ADMINSET_SETTING_ZIGBEESENSITIVITY.ELEMENTS.TEXTS.LINE_02_ITEM).H, Gravity.CENTER, TextColor_Normal, nFontSize_Menu, bFontNonBold, ID.SCREENS.ADMINSET_SETTING_ZIGBEESENSITIVITY.ELEMENTS.TEXTS.LINE_02_ITEM);
            ViewRegistration(layout, Text_Line_02_Item, getPosition(ID.SCREENS.ADMINSET_SETTING_ZIGBEESENSITIVITY.ELEMENTS.TEXTS.LINE_02_ITEM).X, getPosition(ID.SCREENS.ADMINSET_SETTING_ZIGBEESENSITIVITY.ELEMENTS.TEXTS.LINE_02_ITEM).Y);
            Text_Line_02_Item.setText(strText_Line_02_Item);

            Text_Line_03_Item = new WpadTextView(context, false, getPosition(ID.SCREENS.ADMINSET_SETTING_ZIGBEESENSITIVITY.ELEMENTS.TEXTS.LINE_03_ITEM).W, getPosition(ID.SCREENS.ADMINSET_SETTING_ZIGBEESENSITIVITY.ELEMENTS.TEXTS.LINE_03_ITEM).H, Gravity.CENTER, TextColor_Normal, nFontSize_Instruction, bFontNonBold, ID.SCREENS.ADMINSET_SETTING_ZIGBEESENSITIVITY.ELEMENTS.TEXTS.LINE_03_ITEM);
            ViewRegistration(layout, Text_Line_03_Item, getPosition(ID.SCREENS.ADMINSET_SETTING_ZIGBEESENSITIVITY.ELEMENTS.TEXTS.LINE_03_ITEM).X, getPosition(ID.SCREENS.ADMINSET_SETTING_ZIGBEESENSITIVITY.ELEMENTS.TEXTS.LINE_03_ITEM).Y);
            Text_Line_03_Item.setText(strText_Line_03_Item);

            ((MainActivity) mContext).setAutoScreenChange(ID.SCREENS.Main, MainActivity.nAdminScreenTimeout);
        } catch (Exception e) {
            Log.e(TAG, "[Exception] ADMINSET_SETTING_ZIGBEESENSITIVITY(Context context, RelativeLayout layout)");
            e.printStackTrace();
        }
    }

    private void LOG(String log) {
        if (bLOG) Log.v(TAG, log);
    }

    private void LOG_DEBUG(String log) {
        if (bLOG_DEBUG) Log.d(TAG, log);
    }

    private void LOG_INFO(String log) {
        if (bLOG_INFO) Log.i(TAG, log);
    }

    protected void Initialize() {
        try {
            nZigBee_Sensitivity = ConfigValue.nZigBeeSensitivity;
            LOG("[Initialize] nZigBee_Sensitivity [" + nZigBee_Sensitivity + "]");
        } catch (Exception e) {
            Log.e(TAG, "[Exception] Initialize()");
            e.printStackTrace();
        }
    }

    protected void onClose() {
        try {
            LOG("------------------ [onClose - AdminSet_Setting_ZigBeeSensitivity] -------------------");
            if (mHandler != null) {
                mHandler.removeMessages(0);
                mHandler.removeMessages(1);
            }
        } catch (Exception e) {
            Log.e(TAG, "[Exception] onClose()");
            e.printStackTrace();
        }
        super.onClose();
    }

    @Override
    protected void onBrReceive(Intent intent) {
        try {
            LOG("[onBrReceive] Intent : " + intent);
        } catch (Exception e) {
            Log.e(TAG, "[Exception] onBrReceive(intent)");
            e.printStackTrace();
        }
        super.onBrReceive(intent);
    }

    protected void onKeyDown(int keyCode, KeyEvent event) {
        try {
            LOG("[onKeyDown] keyCode [" + keyCode + "], event [" + event + "]");
            if (keyCode == Declare.Button.NUMBER_01) {
                int temp = nZigBee_Sensitivity;
                if ((nZigBee_Sensitivity > MIN_ZIGBEE_SENSITIVITY) && ((temp - 5) >= MIN_ZIGBEE_SENSITIVITY)) {
                    nZigBee_Sensitivity -= 5;
                } else if (nZigBee_Sensitivity == MIN_ZIGBEE_SENSITIVITY) {
                    nZigBee_Sensitivity = MIN_ZIGBEE_SENSITIVITY;
                }
                UpdateScreen();
            } else if (keyCode == Declare.Button.NUMBER_03) {
                int temp = nZigBee_Sensitivity;
                if ((nZigBee_Sensitivity < MAX_ZIGBEE_SENSITIVITY) && ((temp + 5) <= MAX_ZIGBEE_SENSITIVITY)) {
                    nZigBee_Sensitivity += 5;
                } else if (nZigBee_Sensitivity == MAX_ZIGBEE_SENSITIVITY) {
                    nZigBee_Sensitivity = MAX_ZIGBEE_SENSITIVITY;
                }
                UpdateScreen();
            } else if (keyCode == Declare.Button.GUARD) {
                // 설정
                if (!setZigBeeSensitivity(nZigBee_Sensitivity)) {
//    				LOG("seulki - DB SET FAIL");
                    MainActivity.mSound.PlayMent_lobby(R.raw.trylater);
                } else {
//    				LOG("seulki - DB SET SUCCESS");
                    if (!sendSetZigBeeSensitivity()) {
//    					LOG("seulki - 485 FAIL");
                        MainActivity.mSound.PlayMent_lobby(R.raw.trylater);
                    }
//        			else LOG("seulki - 485 SUCCESS");
                }
                super.setChangeScreen(ID.SCREENS.AdminSet_Setting);
            } else if (keyCode == Declare.Button.CANCEL || keyCode == Declare.Button.TACT_CANCEL) {
                // 메뉴화면으로 이동
                super.setChangeScreen(ID.SCREENS.AdminSet_Setting);
            }
        } catch (Exception e) {
            Log.e(TAG, "[Exception] onKeyDown()");
            e.printStackTrace();
        }
    }

    protected void UpdateScreen() {
        try {
            strText_Line_01_Item = String.valueOf(nZigBee_Sensitivity);
            Text_Line_01_Item.setText(strText_Line_01_Item);
        } catch (Exception e) {
            Log.e(TAG, "[Exception] updateScreen()");
            e.printStackTrace();
        }
    }

    public POSITION getPosition(int nID) {
        POSITION position = new POSITION();
        position.SetPosition(0, 0, 480, 272);

        try {
            switch (nID) {
                case ID.SCREENS.ADMINSET_SETTING_ZIGBEESENSITIVITY.ELEMENTS.IMAGES.BACKGROUND:
                    position.SetPosition(0, 0, 480, 272);
                    return position;

                case ID.SCREENS.ADMINSET_SETTING_ZIGBEESENSITIVITY.ELEMENTS.TEXTS.TITLE:
                    position.SetPosition(0, 24, 480, 40);
                    return position;

                case ID.SCREENS.ADMINSET_SETTING_ZIGBEESENSITIVITY.ELEMENTS.TEXTS.LINE_01_ITEM:
                    position.SetPosition(30, 84, 420, 40);
                    return position;

                case ID.SCREENS.ADMINSET_SETTING_ZIGBEESENSITIVITY.ELEMENTS.TEXTS.LINE_02_ITEM:
                    position.SetPosition(30, 134, 420, 40);
                    return position;

                case ID.SCREENS.ADMINSET_SETTING_ZIGBEESENSITIVITY.ELEMENTS.TEXTS.LINE_03_ITEM:
                    position.SetPosition(0, 220, 480, 40);
                    return position;

                default:
                    return position;
            }
        } catch (Exception e) {
            Log.e(TAG, "[Exception] getPosition() : " + e);
            e.printStackTrace();
            return position;
        }
    }

    private boolean sendGetZigBeeSensitivity() {
        try {
            LOG("================ [sendGetZigBeeSensitivity] ================");
            final Request_MultiRF_ZBSensitivity multiRF_zbSensitivity = new Request_MultiRF_ZBSensitivity(mContext);
            if (multiRF_zbSensitivity.send_zigbee_sensitivity_request(MultiReaderPacket.DATA_GET_ZIGBEE_SENSITIVITY)) {
                multiRF_zbSensitivity.setResultCtrl(new iMAPResultCtrl() {
                    @Override
                    public void onResult(iMAPResult eResult) {
                        LOG_INFO("[sendGetZigBeeSensitivity] eResult = " + eResult);
                        if (eResult == iMAPResult.OK) {
                            MainActivity.mSound.Play_lobby(R.raw.resultok);
                            nZigBee_Sensitivity = Integer.parseInt(multiRF_zbSensitivity.strReplyResult);
                            strText_Line_01_Item = String.valueOf(nZigBee_Sensitivity);
                            bGet = true;
                        } else {
                            MainActivity.mSound.PlayMent_lobby(R.raw.trylater);
                            strText_Line_01_Item = strInfoMent_GetResultFail;
                            ((MainActivity) mContext).setAutoScreenChange(ID.SCREENS.AdminSet_Main, 0);
                        }
                        LOG_INFO("[sendSetZigBeeSensitivity] nZigBee_Sensitivity = " + nZigBee_Sensitivity);
                        mHandler.sendEmptyMessage(0);
                    }
                });
                LOG("[sendGetZigBeeSensitivity] strText_Line_01_Item [" + strText_Line_01_Item + "]");
                return true;
            }
            return false;
        } catch (Exception e) {
            Log.e(TAG, "[Exception] sendGetZigBeeSensitivity()");
            e.printStackTrace();
            return false;
        }
    }

    // X'7B ('02: WRITE)
    private boolean sendSetZigBeeSensitivity() {
        try {
            LOG("[sendSetZigBeeSensitivity]");
            final Request_MultiRF_ZBSensitivity multiRF_zbSensitivity = new Request_MultiRF_ZBSensitivity(mContext);
            if (multiRF_zbSensitivity.send_zigbee_sensitivity_request(MultiReaderPacket.DATA_SET_ZIGBEE_SENSITIVITY)) {
                multiRF_zbSensitivity.setResultCtrl(new iMAPResultCtrl() {
                    @Override
                    public void onResult(iMAPResult eResult) {
                        LOG_INFO("[sendSetZigBeeSensitivity] eResult = " + eResult);
                        if (eResult == iMAPResult.OK) {
//                        	LOG("seulki - SEND 0K");
                            MainActivity.mSound.PlayMent_lobby(R.raw.setting);
                            strText_Line_01_Item = String.valueOf(nZigBee_Sensitivity);
                        } else {
//                        	LOG("seulki - SEND NOT OK");
                            MainActivity.mSound.PlayMent_lobby(R.raw.trylater);
                            strText_Line_01_Item = strInfoMent_GetResultFail;
                        }
                        mHandler.sendEmptyMessage(0);
                    }
                });
                return true;
            }
            return false;
        } catch (Exception e) {
            Log.e(TAG, "[Exception] sendZigBeeSensitivity");
            e.printStackTrace();
            return false;
        }
    }

    // DB SET
    private boolean setZigBeeSensitivity(int nSensitivity) {
        try {
            LOG("[setZigBeeSensitivity] nSensitivity [" + nSensitivity + "]");
            ConfigValue.nZigBeeSensitivity = nSensitivity;
            if (!MainActivity.ConfigDBManager.setData(Declare.DBInfo.TABLE_NAME_CONFIG, ConfigValKey.ZigBeeSensitivity, ConfigValue.nZigBeeSensitivity))
                return false;
            return true;
        } catch (Exception e) {
            Log.e(TAG, "[Exception] setZigBeeSensitivity(eSetValue)");
            e.printStackTrace();
            return false;
        }
    }
}
