package com.unibuy.smartdevice.ui;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;

import com.unibuy.smartdevice.AppCompatActivityAbstract;
import com.unibuy.smartdevice.MyApp;
import com.unibuy.smartdevice.databinding.ActivityRestartBinding;
import com.unibuy.smartdevice.devices.Rs232Dev;
import com.unibuy.smartdevice.exception.LogsIOException;
import com.unibuy.smartdevice.exception.LogsUnsupportedOperationException;
import com.unibuy.smartdevice.external.mqtt.MqttManager;
import com.unibuy.smartdevice.tools.HandlerMain;
import com.unibuy.smartdevice.tools.ToastHandlerMain;

import java.util.HashMap;
import java.util.Map;

public class RestartActivity extends AppCompatActivityAbstract {
    public enum Option {
        TOAST(0),
        BACK_HOME(1),
        ;

        private int option;

        public int getOption() {
            return option;
        }

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

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

    private ActivityRestartBinding binding;

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

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

    @Override
    protected HandlerMain setHandlerMain() {
        return new ToastHandlerMain(getCtx(), getLogs()) {
            @Override
            protected void execute(Context context, int commandCode, String message) {
                Option option = optionMap.get(commandCode);

                switch (option) {
                    case TOAST:
                        super.execute(context, commandCode, message);
                        break;
//                    case BACK_HOME:
//                        MyApp.updateLog(getCtx());
//                        getTools().gotoActivity(FontendActivity.class);
//                        break;
                }
            }
        };
    }

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

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

        // 🚩 重啟前統一釋放所有資源
        DeviceResourceManager.getInstance().releaseAllDevices();
        // 延遲幾秒後執行 App 重啟
//        new Handler().postDelayed(() -> {
//            restartApp();
//        }, 1500); // 3 秒後重啟
        restartApp();
    }

    private void restartApp() {
        // 🚩 硬體資源已在 onCreate() 釋放完畢，直接跳購物頁面
        // 不需要 gracefulDisconnect + killProcess：MQTT 已在線，保持連線不中斷
        Intent intent = new Intent(getApplicationContext(), FontendActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
    }


    public static class DeviceResourceManager {

        private static DeviceResourceManager instance;

        private Rs232Dev rs232Dev;
        private DeviceResourceManager() {
            // private constructor
        }

        public static synchronized DeviceResourceManager getInstance() {
            if (instance == null) {
                instance = new DeviceResourceManager();
            }
            return instance;
        }

        // RS232 刷卡機初始化
        public void initRS232() {
            try {
                rs232Dev = new Rs232Dev(MyApp.getInstance().getComPort2ByNFCPay());
            } catch (LogsUnsupportedOperationException e) {
                throw new RuntimeException(e);
            } catch (LogsIOException e) {
                throw new RuntimeException(e);
            }
        }

        public Rs232Dev getRS232() {
            return rs232Dev;
        }

        public void releaseRS232() {
            try {
                if (rs232Dev != null) {
                    rs232Dev.closePort();
                    rs232Dev = null;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }


        // 🚩 重啟前統一呼叫
        public void releaseAllDevices() {
            releaseRS232();
            // 你未來若加上 BLE, NFC, Camera，在這邊統一集中釋放
        }
    }

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


}