package kr.co.icontrols.ilp300_700.screen;

import static android.content.Context.MODE_PRIVATE;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.WindowManager;
import android.widget.RelativeLayout;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import kr.co.icontrols.ilp300_700.MainActivity;
import kr.co.icontrols.ilp300_700.R;
import kr.co.icontrols.ilp300_700.global.Configure.ConfigValue;
import kr.co.icontrols.ilp300_700.global.Configure.SetValue;
import kr.co.icontrols.ilp300_700.global.DataClasses.AccessKeyInfo;
import kr.co.icontrols.ilp300_700.global.DataClasses.POSITION;
import kr.co.icontrols.ilp300_700.global.DataClasses.RemoteIDInfo;
import kr.co.icontrols.ilp300_700.global.Declare;
import kr.co.icontrols.ilp300_700.global.Global;
import kr.co.icontrols.ilp300_700.global.ID;
import kr.co.icontrols.ilp300_700.rfreader.UIDAccessKeyManager;
import kr.co.icontrols.wallpadsupport.WpadImageView;
import kr.co.icontrols.wallpadsupport.WpadScreen;
import kr.co.icontrols.wallpadsupport.WpadTextView;

public class Main extends WpadScreen {

    String TAG = "Main";

    boolean bLOG = true;   // true, false
    boolean bLOG_DEBUG = true;   // true, false
    boolean bLOG_INFO = true;   // true, false
    Context mContext;

    WpadImageView Image_Background;
    WpadImageView Image_Time_AMPM;
    WpadImageView Image_Time_Hour_Tens;
    WpadImageView Image_Time_Hour_Units;
    WpadImageView Image_Time_Split;
    WpadImageView Image_Time_Min_Tens;
    WpadImageView Image_Time_Min_Units;
    WpadTextView Text_Lobby_Info;
    WpadTextView Text_Ment;

    String strText_DeviceName = "";

    int[] nFontSize_Info = {20, 36};
    int[] nFontSize_Ment = {26, 46};

    // IMAGE
    int[] BGImages = {R.drawable.bg_black, R.drawable.bg_black_700};
    int[] RebootBGImages = {R.drawable.reboot_back, R.drawable.reboot_back_700};
    int[] TimeImages_300 = new int[]
            {R.drawable.main_time_0, R.drawable.main_time_1, R.drawable.main_time_2, R.drawable.main_time_3, R.drawable.main_time_4,
                    R.drawable.main_time_5, R.drawable.main_time_6, R.drawable.main_time_7, R.drawable.main_time_8, R.drawable.main_time_9};
    int[] TimeImages_700 = new int[]
            {R.drawable.num_time_0, R.drawable.num_time_1, R.drawable.num_time_2, R.drawable.num_time_3, R.drawable.num_time_4,
                    R.drawable.num_time_5, R.drawable.num_time_6, R.drawable.num_time_7, R.drawable.num_time_8, R.drawable.num_time_9};
    int[][] TimeImages = {TimeImages_300, TimeImages_700};
    int[] AMPMImages_300 = new int[] {R.drawable.image_am, R.drawable.image_pm};
    int[] AMPMImages_700 = new int[] {R.drawable.time_am, R.drawable.time_pm};
    int[][] AMPMImages = {AMPMImages_300, AMPMImages_700};
    int[] SplitImages = {R.drawable.image_dot, R.drawable.time_dot};

    CountDownTimer KeyTimer;   // 멀티키를 인식하기 위한 타이머
    boolean bPressedSTAR = false;
    CountDownTimer InputDelayTimer;   // 메인화면에서 급격한 조작을 방지하기 위한 타이머 (통화 종료후, 통화상태 초기화를 위한 일정 시간후 입력 받음, X초)
    boolean bInputDelay = false;

    String strCryptionTest = "0301570B8900FFFEFFFEFFFEFFFEE0FEC03EC01EC006C006C006C006C006C006F00EFFFEFFFEFFFE000000000000000000000000000000002C23205E4723E33E1F251FBE242C65FE4EADE65E2330A85E251E5D3F359FE07F34AD26DF5027E45A54A98F98000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000";

    //jglee 메인화면
    public Main(Context context, RelativeLayout layout) {
        super(context, layout);
        try {
            LOG("------------------ [START - Main] -------------------");

            mContext = context;
            Initialize();

            super.addBrActionFilter(Intent.ACTION_TIME_TICK);
            super.addBrActionFilter(Declare.PrivateBR.UPDATE_MAINSCREEN);
            super.addBrActionFilter(Declare.PrivateBR.UPDATE_KEYDATA);

            Image_Background = new WpadImageView(context, 0, Declare.DeviceInfo.getScreenSizeFullW(ConfigValue.DEVICE_MODELTYPE), Declare.DeviceInfo.getScreenSizeFullH(ConfigValue.DEVICE_MODELTYPE), Color.TRANSPARENT, 0, ID.SCREENS.MAIN.ELEMENTS.IMAGES.BACKGROUND);
            ViewRegistration(layout, Image_Background, 0, 0);

       /*     // Time ImageView 등록
            Image_Time_AMPM = new WpadImageView(context, 0, getPosition(ID.SCREENS.MAIN.ELEMENTS.IMAGES.TIME_AMPM).W, getPosition(ID.SCREENS.MAIN.ELEMENTS.IMAGES.TIME_AMPM).H, AMPMImages[ConfigValue.DEVICE_MODELTYPE][0], 0, ID.SCREENS.MAIN.ELEMENTS.IMAGES.TIME_AMPM);
            ViewRegistration(layout, Image_Time_AMPM, getPosition(ID.SCREENS.MAIN.ELEMENTS.IMAGES.TIME_AMPM).X, getPosition(ID.SCREENS.MAIN.ELEMENTS.IMAGES.TIME_AMPM).Y);
            Image_Time_Hour_Tens = new WpadImageView(context, 0, getPosition(ID.SCREENS.MAIN.ELEMENTS.IMAGES.TIME_HOUR_TENS).W, getPosition(ID.SCREENS.MAIN.ELEMENTS.IMAGES.TIME_HOUR_TENS).H, TimeImages[ConfigValue.DEVICE_MODELTYPE][0], 0, ID.SCREENS.MAIN.ELEMENTS.IMAGES.TIME_HOUR_TENS);
            ViewRegistration(layout, Image_Time_Hour_Tens, getPosition(ID.SCREENS.MAIN.ELEMENTS.IMAGES.TIME_HOUR_TENS).X, getPosition(ID.SCREENS.MAIN.ELEMENTS.IMAGES.TIME_HOUR_TENS).Y);
            Image_Time_Hour_Units = new WpadImageView(context, 0, getPosition(ID.SCREENS.MAIN.ELEMENTS.IMAGES.TIME_HOUR_UNITS).W, getPosition(ID.SCREENS.MAIN.ELEMENTS.IMAGES.TIME_HOUR_UNITS).H, TimeImages[ConfigValue.DEVICE_MODELTYPE][0], 0, ID.SCREENS.MAIN.ELEMENTS.IMAGES.TIME_HOUR_UNITS);
            ViewRegistration(layout, Image_Time_Hour_Units, getPosition(ID.SCREENS.MAIN.ELEMENTS.IMAGES.TIME_HOUR_UNITS).X, getPosition(ID.SCREENS.MAIN.ELEMENTS.IMAGES.TIME_HOUR_UNITS).Y);
            Image_Time_Split = new WpadImageView(context, 0, getPosition(ID.SCREENS.MAIN.ELEMENTS.IMAGES.TIME_SPLIT_UNITS).W, getPosition(ID.SCREENS.MAIN.ELEMENTS.IMAGES.TIME_SPLIT_UNITS).H, SplitImages[ConfigValue.DEVICE_MODELTYPE], 0, ID.SCREENS.MAIN.ELEMENTS.IMAGES.TIME_SPLIT_UNITS);
            ViewRegistration(layout, Image_Time_Split, getPosition(ID.SCREENS.MAIN.ELEMENTS.IMAGES.TIME_SPLIT_UNITS).X, getPosition(ID.SCREENS.MAIN.ELEMENTS.IMAGES.TIME_SPLIT_UNITS).Y);
            Image_Time_Min_Tens = new WpadImageView(context, 0, getPosition(ID.SCREENS.MAIN.ELEMENTS.IMAGES.TIME_MIN_TENS).W, getPosition(ID.SCREENS.MAIN.ELEMENTS.IMAGES.TIME_MIN_TENS).H, TimeImages[ConfigValue.DEVICE_MODELTYPE][0], 0, ID.SCREENS.MAIN.ELEMENTS.IMAGES.TIME_MIN_TENS);
            ViewRegistration(layout, Image_Time_Min_Tens, getPosition(ID.SCREENS.MAIN.ELEMENTS.IMAGES.TIME_MIN_TENS).X, getPosition(ID.SCREENS.MAIN.ELEMENTS.IMAGES.TIME_MIN_TENS).Y);
            Image_Time_Min_Units = new WpadImageView(context, 0, getPosition(ID.SCREENS.MAIN.ELEMENTS.IMAGES.TIME_MIN_UNITS).W, getPosition(ID.SCREENS.MAIN.ELEMENTS.IMAGES.TIME_MIN_UNITS).H, TimeImages[ConfigValue.DEVICE_MODELTYPE][0], 0, ID.SCREENS.MAIN.ELEMENTS.IMAGES.TIME_MIN_UNITS);
            ViewRegistration(layout, Image_Time_Min_Units, getPosition(ID.SCREENS.MAIN.ELEMENTS.IMAGES.TIME_MIN_UNITS).X, getPosition(ID.SCREENS.MAIN.ELEMENTS.IMAGES.TIME_MIN_UNITS).Y);

            // 로비폰 ID
            Text_Lobby_Info = new WpadTextView(context, false, getPosition(ID.SCREENS.MAIN.ELEMENTS.TEXTS.LOBBY_INFO).W, getPosition(ID.SCREENS.MAIN.ELEMENTS.TEXTS.LOBBY_INFO).H, Gravity.RIGHT, Color.parseColor("#7d7d7d"), nFontSize_Info[ConfigValue.DEVICE_MODELTYPE], false, ID.SCREENS.MAIN.ELEMENTS.TEXTS.LOBBY_INFO);
            ViewRegistration(layout, Text_Lobby_Info, getPosition(ID.SCREENS.MAIN.ELEMENTS.TEXTS.LOBBY_INFO).X, getPosition(ID.SCREENS.MAIN.ELEMENTS.TEXTS.LOBBY_INFO).Y);
            displayDeviceName();

            // 하단 안내 문구 등록
            Text_Ment = new WpadTextView(context, false, getPosition(ID.SCREENS.MAIN.ELEMENTS.TEXTS.MENT).W, getPosition(ID.SCREENS.MAIN.ELEMENTS.TEXTS.MENT).H, Gravity.CENTER, Color.WHITE, nFontSize_Ment[ConfigValue.DEVICE_MODELTYPE], false, ID.SCREENS.MAIN.ELEMENTS.TEXTS.MENT);
            ViewRegistration(layout, Text_Ment, getPosition(ID.SCREENS.MAIN.ELEMENTS.TEXTS.MENT).X, getPosition(ID.SCREENS.MAIN.ELEMENTS.TEXTS.MENT).Y);
            if (Global.bDevicebootup) Text_Ment.setText("세대 호출 : 호수 + 호출");
            else Text_Ment.setText("경비실 호출 : 경비실 + 호출");
*/
            Global.checkEmergencyMode();
            startInputDelayTimer();
            updateScreen();
        } catch (Exception e) {
            Log.e(TAG, "[Exception] Main(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 {
            bPressedSTAR = false;
            MainActivity.mCallController.mCallInfo.resetCallStatus();
            RemoteIDInfo.InitVariables();
            // STT 시험용 코드 (마이크 상시 개방)
//            MainActivity.mCallController.setTalkPath(CALLPATH.MOIP);
        } catch (Exception e) {
            Log.e(TAG, "[Exception] Initialize() : " + e);
            e.printStackTrace();
        }
    }

    @Override
    protected void onClose() {
        try {
            LOG("------------------ [onClose - Main] -------------------");
            CancelAllMsg();
            super.removeBrActionFilter(Intent.ACTION_TIME_TICK);
            super.removeBrActionFilter(Declare.PrivateBR.UPDATE_MAINSCREEN);
        } catch (Exception e) {
            Log.e(TAG, "[Exception] onClose(...) : " + e);
            e.printStackTrace();
        }
        super.onClose();
    }

    @Override
    protected void onBrReceive(Intent intent) {
        try {
            LOG("[onBrReceive] Intent : " + intent);
            if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
                Log.d(TAG, "[MainScreen] (BR) ACTION_TIME_TICK");
                updateScreen();
            }
            else if (intent.getAction().equals(Declare.PrivateBR.UPDATE_MAINSCREEN)) {
                Log.d(TAG, "[MainScreen] (BR) Declare.PrivateBR.UPDATE_MAINSCREEN");
                updateScreenRecovery();
            }
            else if (intent.getAction().equals(Declare.PrivateBR.UPDATE_KEYDATA)) {
                LOG("[onBrReceive] (BR) UPDATE_KEYDATA");
                int value = intent.getIntExtra("data", -1);
                LOG("[onBrReceive] (BR) UPDATE_KEYDATA value : " + value);
                if (Declare.Button.NUMBER_01 <= value && value <= Declare.Button.NUMBER_09) {
                    if (ConfigValue.eLPRole == SetValue.LPRole_CarGate) return;
                    RemoteIDInfo.n1stNumforResicall = value - 7;
                    super.setChangeScreen(ID.SCREENS.Talk_Residence);
                }
                else if (value == Declare.Button.STAR) {
                    if (bPressedSTAR) {
                        if (ConfigValue.eLPRole == SetValue.LPRole_CarGate) return;
                        if (ConfigValue.eAdminAccessPWEnable == SetValue.FALSE) return;
                        super.setChangeScreen(ID.SCREENS.Access_AdminPW);
                    } else {
                        if (KeyTimer != null) {
                            KeyTimer.cancel();
                            KeyTimer = null;
                        }
                        KeyPressTimer();
                        KeyTimer.start();
                        bPressedSTAR = true;
                    }
                }
                else if (value == Declare.Button.SHARP) {
                    if (bPressedSTAR) {
                        super.setChangeScreen(ID.SCREENS.AdminSet_AdminPW);
                    } else {
                        if (ConfigValue.eLPRole == SetValue.LPRole_CarGate) return;
                        Log.d(TAG, "[onKeyDown] eAccessPWSelected = " + ConfigValue.eAccessPWSelected);
                        if (ConfigValue.eAccessPWSelected == SetValue.PublicAccessPW_Selected) {
                            super.setChangeScreen(ID.SCREENS.Access_PublicPW);
                        } else if (ConfigValue.eAccessPWSelected == SetValue.ResiAccessPW_Selected) {
                            super.setChangeScreen(ID.SCREENS.Access_ResidencePW);
                        } else if (ConfigValue.eAccessPWSelected == SetValue.PW_Unselected) {
                        } else {
                            Log.d(TAG, "[onKeyDown] eAccessPWSelected is wrong!!");
                        }
                    }
                }
                else if (value == Declare.Button.GUARD) {
                    super.setChangeScreen(ID.SCREENS.Talk_Guard);
                }
                else if (value == Declare.Button.TACT_GUARD) {
                    LOG("[onKeyDown] TACT_GUARD");
                    Intent intent1 = new Intent();
                    intent1.putExtra("KEYCODE", value);
                    super.setChangeScreen(ID.SCREENS.Talk_Guard, intent1);
                }

            }
        } catch (Exception e) {
            Log.e(TAG, "[Exception] onBrReceive(Intent intent)");
            e.printStackTrace();
        }
        super.onBrReceive(intent);
    }

    @Override
    protected void onKeyDown(int keyCode, KeyEvent event) {
        try {
//            LOG("[onKeyDown] keyCode [" + keyCode + "], event [" + event + "]");
            if (bInputDelay) {
                LOG("[onKeyDown] bInputDelay [" + bInputDelay + "], Ignore Key Input");
                return;
            }

            if (Declare.Button.NUMBER_01 <= keyCode && keyCode <= Declare.Button.NUMBER_09) {
                if (ConfigValue.eLPRole == SetValue.LPRole_CarGate) return;
                RemoteIDInfo.n1stNumforResicall = keyCode - 7;
                super.setChangeScreen(ID.SCREENS.Talk_Residence);
            }
            else if (keyCode == Declare.Button.STAR) {
                if (bPressedSTAR) {
                    if (ConfigValue.eLPRole == SetValue.LPRole_CarGate) return;
                    if (ConfigValue.eAdminAccessPWEnable == SetValue.FALSE) return;
                    super.setChangeScreen(ID.SCREENS.Access_AdminPW);
                } else {
                    if (KeyTimer != null) {
                        KeyTimer.cancel();
                        KeyTimer = null;
                    }
                    KeyPressTimer();
                    KeyTimer.start();
                    bPressedSTAR = true;
                }
            }
            else if (keyCode == Declare.Button.SHARP) {
                if (bPressedSTAR) {
                    super.setChangeScreen(ID.SCREENS.AdminSet_AdminPW);
                } else {
                    if (ConfigValue.eLPRole == SetValue.LPRole_CarGate) return;
                    Log.d(TAG, "[onKeyDown] eAccessPWSelected = " + ConfigValue.eAccessPWSelected);
                    if (ConfigValue.eAccessPWSelected == SetValue.PublicAccessPW_Selected) {
                        super.setChangeScreen(ID.SCREENS.Access_PublicPW);
                    } else if (ConfigValue.eAccessPWSelected == SetValue.ResiAccessPW_Selected) {
                        super.setChangeScreen(ID.SCREENS.Access_ResidencePW);
                    } else if (ConfigValue.eAccessPWSelected == SetValue.PW_Unselected) {
                    } else {
                        Log.d(TAG, "[onKeyDown] eAccessPWSelected is wrong!!");
                    }
                }
            }
            else if (keyCode == Declare.Button.GUARD) {
                super.setChangeScreen(ID.SCREENS.Talk_Guard);
            }
            else if (keyCode == Declare.Button.TACT_GUARD) {
                LOG("[onKeyDown] TACT_GUARD");
                Intent intent = new Intent();
                intent.putExtra("KEYCODE", keyCode);
                super.setChangeScreen(ID.SCREENS.Talk_Guard, intent);
            }
            else if (keyCode == Declare.Button.CANCEL || keyCode == Declare.Button.TACT_CANCEL) {
//                getSensorStatus();
//                String strEncryption = Global.encryptHDCAccessKeyInfo(strCryptionTest);
//                String strDecryption = Global.encryptHDCAccessKeyInfo(strEncryption);
//                Log.w(TAG, "[Cryption] strEncryption : " + strEncryption);
//                Log.w(TAG, "[Cryption] strDecryption : " + strDecryption);

//                String strOriginalPFData = "12345678";
//                String strEncryptedPFData = AES_FingerPrint.encryptFPData(Integer.parseInt(ConfigValue.strDevice_Dong), Integer.parseInt(ConfigValue.strDevice_ID), strOriginalPFData);
//                String strDecryptedPFData = AES_FingerPrint.decryptFPData(Integer.parseInt(ConfigValue.strDevice_Dong), Integer.parseInt(ConfigValue.strDevice_ID), strEncryptedPFData);
//
//                Log.i(TAG, "[onKeyDown] Original");
//                Log.i(TAG, "[onKeyDown] >" + strOriginalPFData);
//                Log.i(TAG, "[onKeyDown] Encrypted");
//                Log.i(TAG, "[onKeyDown] >" + strEncryptedPFData);
//                Log.i(TAG, "[onKeyDown] Decrypted");
//                Log.i(TAG, "[onKeyDown] >" + strDecryptedPFData);
//                MainActivity.mIOInterface.enableADBRemoteConnection();
//                MainActivity.mIOInterface.checkADBRemoteConnectionState();

            }
        } catch (Exception e) {
            Log.e(TAG, "[Exception] onKeyDown(int keyCode, KeyEvent event)");
            e.printStackTrace();
        }
        super.onKeyDown(keyCode, event);
    }

    protected void displayDeviceName() {
        try {
            if (Declare.DeviceInfo.Type == Declare.DeviceType.RESIDENCE) {
                strText_DeviceName = ConfigValue.strDevice_Dong + "동 " + ConfigValue.strDevice_ID + "호 세대";
            } else if (Declare.DeviceInfo.Type == Declare.DeviceType.LOBBY) {
                if ((Integer.parseInt(ConfigValue.strDevice_Dong) % 100) == 0)
                    strText_DeviceName = "관리동 " + ConfigValue.strDevice_ID + "번 로비";
                else
                    strText_DeviceName = ConfigValue.strDevice_Dong + "동 " + ConfigValue.strDevice_ID + "번 로비";
            } else if (Declare.DeviceInfo.Type == Declare.DeviceType.GUARD) {
                if ((Integer.parseInt(ConfigValue.strDevice_Dong) % 100) == 0)
                    strText_DeviceName = "관리동 " + ConfigValue.strDevice_ID + "번 경비";
                else
                    strText_DeviceName = ConfigValue.strDevice_Dong + "동 " + ConfigValue.strDevice_ID + "번 경비";
            }
            Log.d(TAG, "[displayDeviceName] strText_DeviceName [" + strText_DeviceName + "]");
            Text_Lobby_Info.setText(strText_DeviceName);
            Text_Lobby_Info.setSingleLine();
            Text_Lobby_Info.setEllipsize(TextUtils.TruncateAt.END);
        } catch (Exception e) {
            Log.e(TAG, "[Exception] displayDeviceName() : " + e);
            e.printStackTrace();
        }
    }

    protected void updateScreen() {
        try {
            Log.i(TAG, "[updateScreen] Global.bDevicebootup [" + Global.bDevicebootup +"]");
            if (Global.bDevicebootup) {
                // device_bootup.request 성공
                Text_Ment.setText("세대 호출 : 호수 + 호출");

                Image_Background.setImageResource(BGImages[ConfigValue.DEVICE_MODELTYPE]);
//                Image_Time_AMPM.setY(getPosition(ID.SCREENS.MAIN.ELEMENTS.IMAGES.TIME_AMPM).Y);
//                Image_Time_Hour_Tens.setY(getPosition(ID.SCREENS.MAIN.ELEMENTS.IMAGES.TIME_HOUR_TENS).Y);
//                Image_Time_Hour_Units.setY(getPosition(ID.SCREENS.MAIN.ELEMENTS.IMAGES.TIME_HOUR_UNITS).Y);
//                Image_Time_Split.setY(getPosition(ID.SCREENS.MAIN.ELEMENTS.IMAGES.TIME_SPLIT_UNITS).Y);
//                Image_Time_Min_Tens.setY(getPosition(ID.SCREENS.MAIN.ELEMENTS.IMAGES.TIME_MIN_TENS).Y);
//                Image_Time_Min_Units.setY(getPosition(ID.SCREENS.MAIN.ELEMENTS.IMAGES.TIME_MIN_UNITS).Y);

                getCalendar();
                setImage_Time();
            }
            else {
                // device_bootup.request 실패
                if(Text_Ment!=null) Text_Ment.setText("경비실 호출 : 경비실 + 호출");

                Image_Background.setImageResource(RebootBGImages[ConfigValue.DEVICE_MODELTYPE]);
//                Image_Time_AMPM.setY(getPosition(ID.SCREENS.MAIN.ELEMENTS.IMAGES.TIME_AMPM).Y + 272);
//                Image_Time_Hour_Tens.setY(getPosition(ID.SCREENS.MAIN.ELEMENTS.IMAGES.TIME_HOUR_TENS).Y + 272);
//                Image_Time_Hour_Units.setY(getPosition(ID.SCREENS.MAIN.ELEMENTS.IMAGES.TIME_HOUR_UNITS).Y + 272);
//                Image_Time_Split.setY(getPosition(ID.SCREENS.MAIN.ELEMENTS.IMAGES.TIME_SPLIT_UNITS).Y + 272);
//                Image_Time_Min_Tens.setY(getPosition(ID.SCREENS.MAIN.ELEMENTS.IMAGES.TIME_MIN_TENS).Y + 272);
//                Image_Time_Min_Units.setY(getPosition(ID.SCREENS.MAIN.ELEMENTS.IMAGES.TIME_MIN_UNITS).Y + 272);
            }
        } catch (Exception e) {
            Log.e(TAG, "[Exception] updateScreen()");
            e.printStackTrace();
        }
    }

    protected void updateScreenRecovery() {
        try {
            Log.i(TAG, "[updateScreenRecovery] Global.bDevicebootup [" + Global.bDevicebootup +"]");
            if (Global.bDevicebootup) {
                // device_bootup.request 성공
                Text_Ment.setText("세대 호출 : 호수 + 호출");

                Image_Background.setImageResource(BGImages[ConfigValue.DEVICE_MODELTYPE]);
                Image_Time_AMPM.setY(getPosition(ID.SCREENS.MAIN.ELEMENTS.IMAGES.TIME_AMPM).Y);
                Image_Time_Hour_Tens.setY(getPosition(ID.SCREENS.MAIN.ELEMENTS.IMAGES.TIME_HOUR_TENS).Y);
                Image_Time_Hour_Units.setY(getPosition(ID.SCREENS.MAIN.ELEMENTS.IMAGES.TIME_HOUR_UNITS).Y);
                Image_Time_Split.setY(getPosition(ID.SCREENS.MAIN.ELEMENTS.IMAGES.TIME_SPLIT_UNITS).Y);
                Image_Time_Min_Tens.setY(getPosition(ID.SCREENS.MAIN.ELEMENTS.IMAGES.TIME_MIN_TENS).Y);
                Image_Time_Min_Units.setY(getPosition(ID.SCREENS.MAIN.ELEMENTS.IMAGES.TIME_MIN_UNITS).Y);

                getCalendar();
                setImage_Time();
            }
            else {
                // device_bootup.request 실패
                Text_Ment.setText("경비실 호출 : 경비실 + 호출");

                Image_Background.setImageResource(RebootBGImages[ConfigValue.DEVICE_MODELTYPE]);
                Image_Time_AMPM.setY(getPosition(ID.SCREENS.MAIN.ELEMENTS.IMAGES.TIME_AMPM).Y + 272);
                Image_Time_Hour_Tens.setY(getPosition(ID.SCREENS.MAIN.ELEMENTS.IMAGES.TIME_HOUR_TENS).Y + 272);
                Image_Time_Hour_Units.setY(getPosition(ID.SCREENS.MAIN.ELEMENTS.IMAGES.TIME_HOUR_UNITS).Y + 272);
                Image_Time_Split.setY(getPosition(ID.SCREENS.MAIN.ELEMENTS.IMAGES.TIME_SPLIT_UNITS).Y + 272);
                Image_Time_Min_Tens.setY(getPosition(ID.SCREENS.MAIN.ELEMENTS.IMAGES.TIME_MIN_TENS).Y + 272);
                Image_Time_Min_Units.setY(getPosition(ID.SCREENS.MAIN.ELEMENTS.IMAGES.TIME_MIN_UNITS).Y + 272);
            }
        } catch (Exception e) {
            Log.e(TAG, "[Exception] updateScreenRecovery()");
            e.printStackTrace();
        }
    }

    protected void getCalendar() {
        try {
            final Calendar Cal = Calendar.getInstance();

            MainCal.nYear = Cal.get(Calendar.YEAR);   // 년도
            MainCal.nMonth = Cal.get(Calendar.MONTH);   // 월 (1월 ~ 12월 : 0 ~ 11)
            MainCal.nDate = Cal.get(Calendar.DATE);   // 일
            MainCal.nWeekday = Cal.get(Calendar.DAY_OF_WEEK);   // 요일 (일 ~ 토 : 1 ~ 7)
            MainCal.nAMPM = Cal.get(Calendar.AM_PM);   // 오전, 오후 (0 : 오전, 1 : 오후)
            MainCal.nHour = Cal.get(Calendar.HOUR);   // 시
            MainCal.nMin = Cal.get(Calendar.MINUTE);   // 분

            LOG("[getCalendar] CALENDAR [" + MainCal.nYear + "." + Global.ZeroPadding_Head(2, Integer.toString(MainCal.nMonth + 1)) + "." + Global.ZeroPadding_Head(2, Integer.toString(MainCal.nDate)) + " " + MainCal.nWeekday + "]");
            LOG("[getCalendar] CALENDAR [" + MainCal.nAMPM + " " + Global.ZeroPadding_Head(2, Integer.toString(MainCal.nHour)) + ":" + Global.ZeroPadding_Head(2, Integer.toString(MainCal.nMin)) + "]");

            isRebootNeeded();
        } catch (Exception e) {
            Log.e(TAG, "[Exception] getCalendar()");
            e.printStackTrace();
        }
    }

    protected void setImage_Time() {
        try {
            int nAMPM = MainCal.nAMPM;
            if (nAMPM == 1 && MainCal.nHour == 0) MainCal.nHour = 12;
            int nHour_Tens = MainCal.nHour / 10;
            int nHour_Units = MainCal.nHour % 10;
            int nMin_Tens = MainCal.nMin / 10;
            int nMin_Units = MainCal.nMin % 10;
            LOG("[setImage_Time] nHour_Tens [" + nHour_Tens + "], nHour_Units [" + nHour_Units + "], nMin_Tens [" + nMin_Tens + "], nMin_Units [" + nMin_Units + "]");

            Image_Time_AMPM.setImageResource(AMPMImages[ConfigValue.DEVICE_MODELTYPE][nAMPM]);
            Image_Time_Hour_Tens.setImageResource(TimeImages[ConfigValue.DEVICE_MODELTYPE][nHour_Tens]);
            Image_Time_Hour_Units.setImageResource(TimeImages[ConfigValue.DEVICE_MODELTYPE][nHour_Units]);
            Image_Time_Min_Tens.setImageResource(TimeImages[ConfigValue.DEVICE_MODELTYPE][nMin_Tens]);
            Image_Time_Min_Units.setImageResource(TimeImages[ConfigValue.DEVICE_MODELTYPE][nMin_Units]);
        } catch (Exception e) {
            Log.e(TAG, "[Exception] setImage_Time()");
            e.printStackTrace();
        }
    }

    //특정 시간대에 해당 리부트하도록 코드 추가


    //jglee - 2025.03.16 여기서 특정시간에 리부트 하는 코드 추가
    private void isRebootNeeded() {
        try
        {
            test();
        }
        catch (Exception e)
        {
            e.toString();
        }

    }



    Message rebootmsg = null;
    public void Reboot()
    {
        CancelAllMsg();
        rebootmsg = RebootHandler.obtainMessage();
        RebootHandler.sendMessageDelayed(rebootmsg, 3000);
    }

    public void CancelAllMsg()
    {
        if(rebootmsg!=null)
            RebootHandler.removeCallbacksAndMessages(rebootmsg);
    }

    public void test()
    {
        final String PREFS_NAME = "AppPrefs";
        // * 대우로비폰 먹통 증상 개선 시나리오 1 * - 매일 12, 6AM / 12, 6PM (시간 간격) 터치IC 리셋 기능 추가 => 매 시간마다 리셋으로 변경
        Calendar calendar = Calendar.getInstance();
        int nHours = calendar.get(Calendar.HOUR);
        int nMins = calendar.get(Calendar.MINUTE);
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        String strAMPM = calendar.get(Calendar.AM_PM) == Calendar.AM ? "AM" : "PM";
        Log.d(TAG, "[updateTime] Current Time [" + nHours + ":" + nMins + " " + strAMPM + "]");


        // * 시나리오 2 * - 매일 3AM 메인화면일 경우 대기상태라고 판단하여 리셋, 아닐 경우 사용자 조작을 1분마다 체크
        String sharedKey = "LOBBY_RESET_3AM";
        //if (nHours == 3 && strAMPM.equalsIgnoreCase("AM")  && day % 10 == 5) -> 5일 새벽3시
        // 변경 요청 매일 새벽 3시
        if (nHours == 2 && strAMPM.equalsIgnoreCase("AM"))
        {
            if (Global.nCurrentScreenID == ID.SCREENS.Main) {
                long strReset = getTime();//
                Log.d(TAG, "[updateTime] strReset [" + strReset + "]");
                if (strReset == -1) {
                    // 리셋 후 현재 날짜 저장하여 추후 리셋 여부 판단
                    //Reboot 하는 시간을 저장

                    long currentDate = SaveTime();

                    Log.d(TAG, "[updateTime] ************ startSystemReboot!!!!! - " + currentDate);
                    Reboot();
                }
                else {
                    // 전날 날짜(오늘 날짜 - 1)가 SharedPreference Value 와 동일할 경우 리셋
                    // 리셋 이후 오늘 날짜 저장
                    long reboot_time = getTime();

                    Calendar reboot_calendar = Calendar.getInstance();
                    reboot_calendar.setTimeInMillis(reboot_time);

                    Calendar current_calendar = Calendar.getInstance();

                    Log.d(TAG, "[updateTime] value [" + CalandertoString(current_calendar) + "], reboot_time [" + CalandertoString(reboot_calendar) + "]");
                    if (current_calendar.after(reboot_time)) {

                        Log.d(TAG, "[updateTime] today [" + CalandertoString(current_calendar) + "]");

                        SaveTime();
                        Log.d(TAG, "[updateTime] ************ startSystemReboot!!!!! - ");
                        Reboot();
                    }
                    else {
                        Log.w(TAG, "[updateTime] Already Reset!!!");
                    }
                }
            }
            else {
                Log.w(TAG, "[updateTime] nCurrentScreenID [" + Global.nCurrentScreenID + "] is not MAIN!!!");
            }
        }
    }

    public long SaveTime()
    {
        final String PREFS_NAME = "AppPrefs";
        String sharedKey = "LOBBY_RESET_3AM_Test";
        SharedPreferences sharedPreferences = mContext.getApplicationContext().getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        Calendar save_calendar = Calendar.getInstance();
        save_calendar.add(Calendar.DAY_OF_MONTH, 1);
        //save_calendar.add(Calendar.MINUTE, 2);
        long currentDate = save_calendar.getTimeInMillis();
        editor.putLong(sharedKey, currentDate);
        editor.apply();

        return currentDate;
    }

    public long getTime()
    {
        final String PREFS_NAME = "AppPrefs";
        String sharedKey = "LOBBY_RESET_3AM_Test";
        SharedPreferences prefs = mContext.getApplicationContext().getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        long strReset = prefs.getLong(sharedKey, -1);
        return strReset;
    }

    public String CalandertoString(Calendar calendar)
    {
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1; // 월은 0부터 시작하므로 +1 필요
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        int hour = calendar.get(Calendar.HOUR_OF_DAY); // 24시간 형식
        int minute = calendar.get(Calendar.MINUTE);
        int second = calendar.get(Calendar.SECOND);

        // String.format()을 이용한 문자열 출력
        String formattedDate = String.format("%04d-%02d-%02d %02d:%02d:%02d",
                year, month, day, hour, minute, second);

        return formattedDate;
    }








    public Handler RebootHandler = new Handler(Looper.getMainLooper()) {
        public void handleMessage(Message msg) {
            Log.d(TAG, "jglee - Reboot");
            //MainActivity.mIOInterface.Reboot(0);
        }
    };


    protected void KeyPressTimer() {
        try {
            if (KeyTimer != null) {
                KeyTimer.cancel();
                KeyTimer = null;
            }

            KeyTimer = new CountDownTimer(1000, 1000) {
                @Override
                public void onTick(long millisUntilFinished) {
                    LOG("[KeyPressTimer] onTick!!");
                }

                @Override
                public void onFinish() {
                    LOG("[KeyPressTimer] onFinish!!");
                    bPressedSTAR = false;
                }
            };
        } catch (Exception e) {
            Log.e(TAG, "[Exception] KeyPressTimer()");
            e.printStackTrace();
        }
    }

    private void startInputDelayTimer() {
        try {
            LOG("[startInputDelayTimer] ========== START ==========");
            bInputDelay = true;
            if (InputDelayTimer != null) {
                InputDelayTimer.cancel();
                InputDelayTimer = null;
            }

            InputDelayTimer = new CountDownTimer(3000, 1000) {
                @Override
                public void onTick(long millisUntilFinished) {
                    LOG("[startInputDelayTimer] onTick!!");
                }

                @Override
                public void onFinish() {
                    LOG("[startInputDelayTimer] onFinish!!");
                    bInputDelay = false;
                    quitInputDelayTimer();
                }
            };
            InputDelayTimer.start();
        } catch (Exception e) {
            Log.e(TAG, "[Exception] startInputDelayTimer()");
            e.printStackTrace();
        }
    }

    private void quitInputDelayTimer() {
        try {
            LOG("[quitInputDelayTimer] ========== START ==========");
            if (InputDelayTimer != null) {
                InputDelayTimer.cancel();
            }
            InputDelayTimer = null;
        } catch (Exception e) {
            Log.e(TAG, "[Exception] quitInputDelayTimer()");
            e.printStackTrace();
        }
    }

    public POSITION getPosition(int nID) {
        POSITION position = new POSITION();
        position.SetPosition(0, 0, 480, 272);
        try {
            switch (nID) {
                case ID.SCREENS.MAIN.ELEMENTS.IMAGES.BACKGROUND:
                    if (ConfigValue.DEVICE_MODELTYPE == Global.MODEL_ILP_700) position.SetPosition(0, 0, 800, 480);
                    else position.SetPosition(0, 0, 480, 272);
                    return position;

                case ID.SCREENS.MAIN.ELEMENTS.IMAGES.TIME_AMPM:
                    if (ConfigValue.DEVICE_MODELTYPE == Global.MODEL_ILP_700) {
                        if (Global.bDevicebootup) position.SetPosition(86, 153, 98, 49);
                        else position.SetPosition(86, 153 + 480, 98, 49);
                    }
                    else {
                        if (Global.bDevicebootup) position.SetPosition(44, 67, 70, 50);
                        else position.SetPosition(44, 67 + 272, 70, 50);
                    }
                    return position;

                case ID.SCREENS.MAIN.ELEMENTS.IMAGES.TIME_HOUR_TENS:
                    if (ConfigValue.DEVICE_MODELTYPE == Global.MODEL_ILP_700) {
                        if (Global.bDevicebootup) position.SetPosition(203, 144, 91, 136);
                        else position.SetPosition(203, 144 + 480, 91, 136);
                    }
                    else {
                        if (Global.bDevicebootup) position.SetPosition(114, 67, 63, 88);
                        else position.SetPosition(114, 67 + 272, 63, 88);
                    }
                    return position;

                case ID.SCREENS.MAIN.ELEMENTS.IMAGES.TIME_HOUR_UNITS:
                    if (ConfigValue.DEVICE_MODELTYPE == Global.MODEL_ILP_700) {
                        if (Global.bDevicebootup) position.SetPosition(305, 144, 91, 136);
                        else position.SetPosition(305, 144 + 272, 91, 136);
                    }
                    else {
                        if (Global.bDevicebootup) position.SetPosition(177, 67, 63, 88);
                        else position.SetPosition(177, 67 + 272, 63, 88);
                    }
                    return position;

                case ID.SCREENS.MAIN.ELEMENTS.IMAGES.TIME_SPLIT_UNITS:
                    if (ConfigValue.DEVICE_MODELTYPE == Global.MODEL_ILP_700) {
                        if (Global.bDevicebootup) position.SetPosition(420, 146, 18, 132);
                        else position.SetPosition(420, 146 + 480, 18, 132);
                    }
                    else {
                        if (Global.bDevicebootup) position.SetPosition(240, 67, 30, 88);
                        else position.SetPosition(240, 67 + 272, 30, 88);
                    }
                    return position;

                case ID.SCREENS.MAIN.ELEMENTS.IMAGES.TIME_MIN_TENS:
                    if (ConfigValue.DEVICE_MODELTYPE == Global.MODEL_ILP_700) {
                        if (Global.bDevicebootup) position.SetPosition(462, 144, 91, 136);
                        else position.SetPosition(462, 144 + 480, 91, 136);
                    }
                    else {
                        if (Global.bDevicebootup) position.SetPosition(270, 67, 63, 88);
                        else position.SetPosition(270, 67 + 272, 63, 88);
                    }
                    return position;

                case ID.SCREENS.MAIN.ELEMENTS.IMAGES.TIME_MIN_UNITS:
                    if (ConfigValue.DEVICE_MODELTYPE == Global.MODEL_ILP_700) {
                        if (Global.bDevicebootup) position.SetPosition(564, 144, 91, 136);
                        else position.SetPosition(564, 144 + 480, 91, 136);
                    }
                    else {
                        if (Global.bDevicebootup) position.SetPosition(333, 67, 63, 88);
                        else position.SetPosition(333, 67 + 272, 63, 88);
                    }
                    return position;

                case ID.SCREENS.MAIN.ELEMENTS.IMAGES.NOTICE_EMERGENCY:
                    if (ConfigValue.DEVICE_MODELTYPE == Global.MODEL_ILP_700) position.SetPosition(0, 148, 800, 130);
                    else position.SetPosition(52, 81, 376, 84);
                    return position;

                case ID.SCREENS.MAIN.ELEMENTS.IMAGES.NOTICE_RFREADER:
                    if (ConfigValue.DEVICE_MODELTYPE == Global.MODEL_ILP_700) position.SetPosition(0, 0, 117, 95);
                    else position.SetPosition(17, 3, 65, 51);
                    return position;

                case ID.SCREENS.MAIN.ELEMENTS.TEXTS.LOBBY_INFO:
                    if (ConfigValue.DEVICE_MODELTYPE == Global.MODEL_ILP_700) position.SetPosition(3, 3, 775, 65);
                    else position.SetPosition(3, 3, 467, 36);
                    return position;

                case ID.SCREENS.MAIN.ELEMENTS.TEXTS.MENT:
                    if (ConfigValue.DEVICE_MODELTYPE == Global.MODEL_ILP_700) position.SetPosition(0, 381, 800, 99);
                    else position.SetPosition(0, 216, 480, 56);
                    return position;

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

    private void KeyTest() {
        try {
            AccessKeyInfo KeyInfo = new AccessKeyInfo();
            KeyInfo = UIDAccessKeyManager.getDBKey("FDE1F1C28000007");
            if (KeyInfo != null) KeyInfo.printValue();
            KeyInfo = UIDAccessKeyManager.getDBKey("FDE1F1C28000009");
            if (KeyInfo != null) KeyInfo.printValue();
            KeyInfo = UIDAccessKeyManager.getDBKey("FDA1F1C28000008");
            if (KeyInfo != null) KeyInfo.printValue();
        } catch (Exception e) {
            Log.e(TAG, "[Exception] KeyTest()");
            e.printStackTrace();
        }
    }

    static class MainCal {
        static int nYear;   // 년도
        static int nMonth;   // 월
        static int nDate;   // 일
        static int nWeekday;   // 요일
        static int nAMPM;   // 오전, 오후
        static int nHour;   // 시
        static int nMin;   // 분
    }

    int nTestCnt = 0;
    private void testANR() {
        try {
            while (true) {
                nTestCnt++;
                Thread.sleep(1000);
            }
        } catch (Exception e) {
            Log.e(TAG, "[Exception] testANR()");
            e.printStackTrace();
        }
    }

}