package com.unibuy.smartdevice;

import static android.view.View.VISIBLE;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Looper;
import android.view.View;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.unibuy.smartdevice.controller.DevXinYuanController;
import com.unibuy.smartdevice.databinding.ActivityHomeBinding;
import com.unibuy.smartdevice.devices.DevNFCPay;
import com.unibuy.smartdevice.devices.Rs232Dev;
import com.unibuy.smartdevice.devices.SlotField;
import com.unibuy.smartdevice.exception.ErrorCode;
import com.unibuy.smartdevice.exception.LogsEmptyException;
import com.unibuy.smartdevice.exception.LogsFileNullException;
import com.unibuy.smartdevice.exception.LogsIOException;
import com.unibuy.smartdevice.exception.LogsParseException;
import com.unibuy.smartdevice.exception.LogsSettingEmptyException;
import com.unibuy.smartdevice.exception.LogsUnsupportedOperationException;
import com.unibuy.smartdevice.external.HttpAPI;
import com.unibuy.smartdevice.tools.HandlerMain;
import com.unibuy.smartdevice.tools.HandlerMainScheduler;
import com.unibuy.smartdevice.tools.ToastHandlerMain;
import com.unibuy.smartdevice.tools.Tools;
import com.unibuy.smartdevice.ui.FontendActivity;
import com.unibuy.smartdevice.ui.RestartActivity;
import com.unibuy.smartdevice.ui.RestartHostActivity;
import com.unibuy.smartdevice.ui.devs.electric.ElectricFragment;
import com.unibuy.smartdevice.ui.devs.vmc.VmcFragment;
import com.unibuy.smartdevice.ui.dialog.BuyDialog;
import com.unibuy.smartdevice.ui.dialog.FontendPickupCodeDialog;
import com.unibuy.smartdevice.ui.tools.ImageGlide;
import com.unibuy.smartdevice.ui.tools.VideoEoxPlayer;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

public class HomeActivity extends AppCompatActivityAbstract {
    public enum Option {
        TOAST(0),
        REPORT_AND_SHOT_TIME(5),
        RESTART_HOST(7),
        RESET_SLOTNO(49),
        ;

        private int option;

        public int getOption() {
            return option;
        }

        Option(int option) {
            this.option = option;
        }
    }

    public static final Map<Integer, FontendActivity.Option> optionMap = new HashMap<>();
    static {
        for (FontendActivity.Option option : FontendActivity.Option.values()) {
            optionMap.put(option.getOption(), option);
        }
    }
    private ActivityHomeBinding binding;
    private static VideoEoxPlayer videoEoxPlayer;

    // ✅ 廣告更新監聽器：MQTT 廣告同步完成後自動刷新待機廣告播放器
    private final BroadcastReceiver adUpdateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            getLogs().info("🔔 [HomeActivity] 收到 ACTION_AD_UPDATED 廣播，準備刷新待機頁廣告播放器...");
            // 🔹 清除 Glide 記憶體快取，避免拿到舊的圖片 Bitmap
            Glide.get(context).clearMemory();
            // 使用 postDelayed 確保 DB 寫入完成後再刷新
            new android.os.Handler(Looper.getMainLooper()).postDelayed(() -> {
                if (!isFinishing() && !isDestroyed()) {
                    startOnSwitchFragment();
                    getLogs().info("✅ [HomeActivity] 待機頁廣告播放器已重建");
                } else {
                    getLogs().info("⚠️ [HomeActivity] Activity 已銷毀，取消刷新廣告播放器");
                }
            }, 500);
        }
    };

    private long lastReportTime = 0;

    private static ReportShotTimeByScheduler reportOnScheduler;

    @Override
    protected Context setCtx() {
        return this;
    }

    @Override
    protected Class<?> setCls() {
        return getClass();
    }

    @Override
    protected HandlerMain setHandlerMain() {
        return new ToastHandlerMain(getCtx(), getLogs()) {
            private FontendActivity.AddProductOnCountdown addProductOnCountdown;

            @Override
            protected void execute(Context context, int commandCode, String message) {
                FontendActivity.Option option = optionMap.get(commandCode);

                switch (option) {
                    case TOAST:
                        super.execute(context, commandCode, message);
                        break;
                    case REPORT_AND_SHOT_TIME:
                        String ver = "";
                        try {
                            PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
                            ver = packageInfo.versionName;
                        } catch (PackageManager.NameNotFoundException e) {
                            ver = "0";
                        }

                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
                        String timeByNow = sdf.format(new Date());

                        String timeByM = new SimpleDateFormat("HH:mm").format(new Date());
                        if (timeByM.equals("23:45")) {
                            new NfcCheckout(this).start();
                        }
                        if (timeByM.equals("23:59") || timeByM.equals("04:00") || timeByM.equals("08:00")
                                || timeByM.equals("12:00") || timeByM.equals("16:00") || timeByM.equals("20:00")) {
                            android.content.SharedPreferences prefs = getSharedPreferences("AppRestartPrefs", Context.MODE_PRIVATE);
                            String today = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(new Date());
                            String currentSlot = today + " " + timeByM;
                            String lastRestartSlot = prefs.getString("last_restart_slot", "");

                            if (!currentSlot.equals(lastRestartSlot)) {
                                prefs.edit().putString("last_restart_slot", currentSlot).commit();
                                getLogs().info("當前時間：" + timeByM + "，符合條件，啟動 RestartAPP2 (硬重啟等待模式)...");
                                new RestartAPP2(this).start();
                            } else {
                                getLogs().debug("當前時間時段 " + currentSlot + " 已執行過重啟，跳過重複啟動");
                            }
                        }

                        //每半小時主動連線下位機一次
                        String minutePart = timeByM.split(":")[1]; // 取得 "mm" 部分
                        if (minutePart.equals("00") || minutePart.equals("30")) {
                            getLogs().info("當前時間：" + timeByM + "，符合條件，執行 CMUHAutoRun...");
//                            new CMUHAutoRun(this).start();
                        }

                        getLogs().update("ThreadCount", String.valueOf(Tools.threadCount()));
                        String tc = getLogs().getMessage();
                        getLogs().update("ViceoCount", String.valueOf(VideoEoxPlayer.getExoPlayerTotal()));
                        String vc = getLogs().getMessage();
                        getLogs().clearMessage();

                        Tools.threadInfos();

                        DevXinYuanController.setVersion(ver);
                        getLogs().update("Temperature", String.valueOf(DevXinYuanController.getTemperature()),"℃");
                        getLogs().clearMessage();

                        try {
                            // httpAPI.detectHost();
                        } catch (Exception e) {
                            // getLogs().warning(e);
                        }

                        String timeByS = new SimpleDateFormat("ss").format(new Date());
                        timeByS = String.valueOf(Integer.valueOf(timeByS)/10*10);
                        getLogs().debug("timeByS:" + timeByS);

                        /// /機器B022 API

                        // 在您的定時任務中：
                        String[] timeParts = timeByM.split(":");
                        if (timeParts.length >= 2) {
                            String minute = timeParts[1];
                            if (minute.matches("00|10|20|30|40|50")) {
                                long currentTime = System.currentTimeMillis();
                                // 確保距離上次執行至少間隔 9 分鐘（540000 毫秒）
                                if (currentTime - lastReportTime >= 540000) {
                                    try {
                                        // httpAPI.deviceReport();
                                        lastReportTime = currentTime;
                                    } catch (Exception e) {
                                        // e.printStackTrace();
                                    }
                                }
                            }
                        }

                        break;
                    case RESTART_HOST:
                        new RestartHost(this).start();
                        break;
                    case RESET_SLOTNO:
                        new ResetSlotNo(this).start();
                        break;
                }
            }
        };
    }

    private HttpAPI httpAPI;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 🚩 進入首頁時強制清空購物車，確保機台處於閒置狀態，避免 MQTT 遠端重啟被阻擋
        MyApp.getInstance().getBuyList().clear();

        // 啟動鎖定檢查
        com.unibuy.smartdevice.database.SettingsDao settingsDao = new com.unibuy.smartdevice.database.SettingsDao(getApplicationContext());
        if (settingsDao.isMachineLocked()) {
            settingsDao.close();
            Intent intent = new Intent(this, com.unibuy.smartdevice.ui.MaintenanceActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
            finish();
            return;
        }
        settingsDao.close();

        if (AppEntry.isCmuh()) {
            Intent intent = new Intent(this, FontendActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
            finish();
            return;
        }

        binding = ActivityHomeBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        httpAPI = new HttpAPI(getHandlerMain());

        binding.startButton.setOnClickListener(v -> {
            // 經過 RestartActivity 釋放硬體資源（RS232 等），再跳購物頁面
            // RestartActivity 已修改為不再 gracefulDisconnect + killProcess，MQTT 連線不中斷
            getTools().gotoActivity(RestartActivity.class);
            finish();
        });

        if (reportOnScheduler != null) {
            reportOnScheduler.shutdown();
        }

        reportOnScheduler = new ReportShotTimeByScheduler(getHandlerMain());
        reportOnScheduler.start(1L, 10L, TimeUnit.SECONDS);

        startOnSwitchFragment();

        // ✅ 註冊廣告更新監聽
        IntentFilter adFilter = new IntentFilter("com.unibuy.smartdevice.ACTION_AD_UPDATED");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            registerReceiver(adUpdateReceiver, adFilter, Context.RECEIVER_NOT_EXPORTED);
        } else {
            registerReceiver(adUpdateReceiver, adFilter);
        }
    }

    public void startOnSwitchFragment() {
        try {
            stopOnSwitchFragment(); // 防止重複建立

            videoEoxPlayer = new VideoEoxPlayer(getCtx());

            getHandlerMain().getHandler().postDelayed(() -> {
                if (isFinishing() || isDestroyed()) return;
                try {
//                    videoEoxPlayer.playMedia(binding.videoView, binding.imageAd); // ✅ 同時支援影片與圖片輪播
                    videoEoxPlayer.playMediaByFlag("3", binding.videoView, binding.imageAd); // ✅ 同時支援影片與圖片輪播
                } catch (Exception e) {
                    getLogs().warning(e);
                }
            }, 500);
        } catch (Exception e) {
            getLogs().warning(e);
        }
    }

    public void stopOnSwitchFragment() {
        if (videoEoxPlayer != null) {
            videoEoxPlayer.stopVideo(); // ✅ 清除影片與圖片播放資源
            videoEoxPlayer = null;
        }
    }

    public void ReSetAPP(){
        Intent intent = new Intent(getApplicationContext(), FontendActivity.class);
        // 清空所有 Task，重新啟動
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);

        // 建議搭配 finishAffinity()，確保所有舊的 Activity 都被清掉
        //finishAffinity();

        // 完全不需要 killProcess()
    }

    public void ReSetAPP2(){
        getLogs().info("🔄HomeActivity - Scheduled Hard App restarting via gracefulDisconnect...");
        com.unibuy.smartdevice.external.mqtt.MqttManager.getInstance().gracefulDisconnect(() -> {
            new android.os.Handler(android.os.Looper.getMainLooper()).post(() -> {
                Intent intent = new Intent(getApplicationContext(), AppEntry.initialActivity());
                // 清空所有 Task，重新啟動
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK
                        | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                startActivity(intent);

                // 建議搭配 finishAffinity()，確保所有舊的 Activity 都被清掉
                finishAffinity();
                
                android.os.Process.killProcess(android.os.Process.myPid());
            });
        });
    }


    private class RestartAPP extends HandlerMainScheduler {
        private int testCount = 0;
        public RestartAPP(HandlerMain handlerMain) {
            super(handlerMain);
            testCount = 0;
        }

        @Override
        protected HandlerMain setHandlerMain() {
            return getSrcHandlerMain();
        }

        @Override
        protected void execute(HandlerMain handlerMain) {
            for (int testIndex=0; testIndex < 30; testIndex++) {
                if (testCount < 3) {
                    if (!MyApp.getInstance().isMachineBusy()) {
                        getLogs().debug("RestartHost testCount:" + testCount);
                        testCount++;
                    } else {
                        testCount = 0;
                    }

                    try {
                        Thread.sleep(1000*20);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                } else {
                    break;
                }
            }

            if (testCount < 3) {
                return;
            }

            ReSetAPP();
        }

        @Override
        protected Class<?> setCls() {
            return getClass();
        }
    }

    /**
     * 【硬重啟】確認閒置秒數後執行真重啟。
     * - 只要閒置 >= 90 秒，立刻啟動 HomeActivity 並 killProcess。
     * - 若有人正在使用（閒置 < 90 秒），則等待 5 秒後再重新判斷，最多等待 10 分鐘。
     */
    private class RestartAPP2 extends HandlerMainScheduler {
        public RestartAPP2(HandlerMain handlerMain) {
            super(handlerMain);
        }
        @Override
        protected HandlerMain setHandlerMain() { return getSrcHandlerMain(); }
        @Override
        protected void execute(HandlerMain handlerMain) {
            // 最多等待 10 分鐘（120 次 * 5 秒），確保機台有機會重啟
            for (int i = 0; i < 120; i++) {
                long idle = MyApp.getInstance().getIdleSeconds();
                boolean isBusy = MyApp.getInstance().isMachineBusy();

                if (idle >= 90 && !isBusy) {
                    getLogs().info("RestartAPP2：閒置 " + idle + " 秒且機台不忙碌，執行真重啟");
                    new android.os.Handler(android.os.Looper.getMainLooper()).post(() -> {
                        ReSetAPP2();
                    });
                    return;
                }
                getLogs().debug("RestartAPP2：閒置 " + idle + " 秒，BusyReason:" + MyApp.getInstance().getBusyReason() + "，等待 5 秒後重新判斷 (" + (i+1) + "/120)");
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    return;
                }
            }
            getLogs().info("RestartAPP2：等待超過 10 分鐘仍有人在使用，放棄本次重啟");
        }
        @Override
        protected Class<?> setCls() { return getClass(); }
    }

    private class RestartHost extends HandlerMainScheduler {
        private int testCount = 0;
        public RestartHost(HandlerMain handlerMain) {
            super(handlerMain);
            testCount = 0;
        }

        @Override
        protected HandlerMain setHandlerMain() {
            return getSrcHandlerMain();
        }

        @Override
        protected void execute(HandlerMain handlerMain) {
            for (int testIndex=0; testIndex < 30; testIndex++) {
                if (testCount < 3) {
                    if (!MyApp.getInstance().isMachineBusy()) {
                        getLogs().debug("RestartHost testCount:" + testCount);
                        testCount++;
                    } else {
                        testCount = 0;
                    }

                    try {
                        Thread.sleep(1000*20);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                } else {
                    break;
                }
            }

            if (testCount < 3) {
                return;
            }

            getTools().gotoActivity(RestartHostActivity.class);
        }

        @Override
        protected Class<?> setCls() {
            return getClass();
        }
    }

    private static class NfcCheckout extends HandlerMainScheduler {
        private int testCount = 0;
        public NfcCheckout(HandlerMain handlerMain) {
            super(handlerMain);
            testCount = 0;
        }

        @Override
        protected HandlerMain setHandlerMain() {
            return getSrcHandlerMain();
        }

        @Override
        protected void execute(HandlerMain handlerMain) {
            for (int testIndex=0; testIndex < 30; testIndex++) {
                if (testCount < 3) {
                    if (!MyApp.getInstance().isMachineBusy()) {
                        getLogs().debug("NfcCheckout testCount:" + testCount);
                        testCount++;
                    } else {
                        testCount = 0;
                    }

                    try {
                        Thread.sleep(1000*20);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                } else {
                    break;
                }
            }

            if (testCount < 3) {
                return;
            }

            try {
                Rs232Dev comPort2 = new Rs232Dev(MyApp.getInstance().getComPort2ByNFCPay());
                DevNFCPay devNFCPay = new DevNFCPay(handlerMain.getContext());
                comPort2.send(devNFCPay.checkout());
                handlerMain.start(getClass().getSimpleName(), "刷卡機結帳啟動");
            } catch (LogsUnsupportedOperationException | LogsIOException e) {
                getLogs().warning(e);
            }
        }

        @Override
        protected Class<?> setCls() {
            return getClass();
        }
    }

    private class ResetSlotNo extends HandlerMainScheduler {
        public ResetSlotNo(HandlerMain handlerMain) {
            super(handlerMain);
        }

        @Override
        protected HandlerMain setHandlerMain() {
            return getSrcHandlerMain();
        }

        @Override
        protected void execute(HandlerMain handlerMain) {

            try {
                httpAPI.reportSlotPost();
            } catch (LogsParseException e) {
                throw new RuntimeException(e);
            } catch (LogsSettingEmptyException e) {
                throw new RuntimeException(e);
            }

        }

        @Override
        protected Class<?> setCls() {
            return getClass();
        }
    }

    private class CMUHAutoRun extends HandlerMainScheduler {
        private int testCount = 0;
        public CMUHAutoRun(HandlerMain handlerMain) {
            super(handlerMain);
            testCount = 0;
        }

        @Override
        protected HandlerMain setHandlerMain() {
            return getSrcHandlerMain();
        }

        @Override
        protected void execute(HandlerMain handlerMain) {
            Looper.prepare();  // ✅ 確保這個執行緒有 Looper
            for (int testIndex=0; testIndex < 30; testIndex++) {
                if (testCount < 3) {
                    if (!MyApp.getInstance().isMachineBusy()) {
                        getLogs().debug("CMUHAutoRun testCount:" + testCount);
                        testCount++;
                    } else {
                        testCount = 0;
                    }

                    try {
                        Thread.sleep(1000*20);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                } else {
                    break;
                }
            }

            if (testCount < 3) {
                return;
            }
            getLogs().info("CMUHAutoRun - 11111111111111111");
            MyApp.getInstance().getDevXinYuanController().addSendBuffer(
                    MyApp.getInstance().getDevXinYuanController().getDevXinYuan().syncPackNo((byte)0x01));
            getLogs().info("CMUHAutoRun - 22222222222222222");

            //Looper.loop();  // ✅ 啟動事件迴圈
            // 👇 安全地結束 Looper，釋放這個 Thread
            Objects.requireNonNull(Looper.myLooper()).quitSafely(); // 或 quit() 根據需求

        }

        @Override
        protected Class<?> setCls() {
            return getClass();
        }
    }

    public class ReportShotTimeByScheduler extends HandlerMainScheduler {
        public ReportShotTimeByScheduler(HandlerMain handlerMain) {
            super(handlerMain);
        }

        @Override
        protected HandlerMain setHandlerMain() {
            return getSrcHandlerMain();
        }

        @Override
        protected void execute(HandlerMain handlerMain) {
            handlerMain.start(getClass().getSimpleName(), HomeActivity.Option.REPORT_AND_SHOT_TIME.getOption(), "start");
        }

        @Override
        protected Class<?> setCls() {
            return getClass();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        finish();  // 當新畫面啟動後自動結束 RestartActivity
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopOnSwitchFragment();
        if (reportOnScheduler != null) {
            reportOnScheduler.shutdown();
        }
        // ✅ 取消註冊廣告更新監聽
        try {
            unregisterReceiver(adUpdateReceiver);
        } catch (Exception e) {
            getLogs().info("unregisterReceiver adUpdateReceiver: " + e.getMessage());
        }
    }
}
