package com.unibuy.smartdevice.ui;

import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;

import com.unibuy.smartdevice.AppCompatActivityAbstract;
import com.unibuy.smartdevice.MyApp;
import com.unibuy.smartdevice.database.SettinglogsDao;
import com.unibuy.smartdevice.databinding.ActivitySettingBinding;
import com.unibuy.smartdevice.exception.LogsParseException;
import com.unibuy.smartdevice.exception.LogsSettingEmptyException;
import com.unibuy.smartdevice.external.HttpAPI;
import com.unibuy.smartdevice.external.StarCloudAPI;
import com.unibuy.smartdevice.tools.HandlerMain;
import com.unibuy.smartdevice.tools.HandlerMainSchedulerOnClick;
import com.unibuy.smartdevice.tools.ToastHandlerMain;
import com.unibuy.smartdevice.tools.Tools;
import com.unibuy.smartdevice.ui.recycler.RecyclerSettingListAdpter;
import com.unibuy.smartdevice.ui.tools.ImageGlide;
import com.unibuy.smartdevice.ui.tools.VideoImageMixedPlayer;
import com.unibuy.smartdevice.utils.LanguageHelper;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SettingActivity extends AppCompatActivityAbstract {
    public enum Option {
        TOAST(0),
        CHECK_AND_SAVE_STATUS(1),
        DATA_RELOAD(2),
        SUCCESS(200),
        FAILED(400),
        ;

        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);
        }
    }

    @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);

                if (option == null) {
                    // 如果拿到未定義的代碼 (例如 404, 500)，視同失敗，關掉進度條並顯示訊息
                    super.execute(context, commandCode, message);
                    binding.progressLayout.setVisibility(View.GONE);
                    binding.buttonBack.setVisibility(View.VISIBLE);
                    return;
                }

                switch (option) {
                    case TOAST:
                        super.execute(context, commandCode, message);
                        break;
                    case CHECK_AND_SAVE_STATUS:
                        super.execute(context, commandCode, message);
                        binding.buttonBack.setVisibility(View.VISIBLE);
                        checkSetting();
                        saveStatusList(context);
                        break;
                    case DATA_RELOAD:
                        binding.buttonBack.setVisibility(View.INVISIBLE);
                        MyApp.getInstance().getMachine().setMachineID(binding.editMachineID.getText().toString());
                        if (binding.radioProd.isChecked()) {
                            MyApp.getInstance().getMachine().setMqttEnv("prod");
                        } else {
                            MyApp.getInstance().getMachine().setMqttEnv("demo");
                        }
                        binding.progressLayout.setVisibility(View.VISIBLE); // 確保進度條顯示
                        try {
                            starCloudAPI.downloadSetting();
                        } catch (Exception e) {
                            getLogs().warning(e);
                            binding.progressLayout.setVisibility(View.GONE);
                            binding.buttonBack.setVisibility(View.VISIBLE);
                        }
                        break;
                    case SUCCESS:
                        super.execute(context, commandCode, message);
                        binding.progressLayout.setVisibility(View.GONE);
                        binding.buttonBack.setVisibility(View.VISIBLE);

                        // 綁定成功後，自動連動執行 B012 同步商品
                        if ("綁定成功".equals(message)) {
                            binding.progressLayout.setVisibility(View.VISIBLE); // 顯示進度條，因為要同步商品
                            starCloudAPI.downloadProductInfo();
                        } else if ("商品下載成功".equals(message)) {
                            binding.progressLayout.setVisibility(View.VISIBLE); // 顯示進度條，同步廣告
                            starCloudAPI.downloadAdvertisement();
                        }

                        checkSetting();
                        saveStatusList(context);
                        break;
                    case FAILED:
                        super.execute(context, commandCode, message);
                        binding.progressLayout.setVisibility(View.GONE);
                        binding.buttonBack.setVisibility(View.VISIBLE);
                        break;
                }
            }
        };
    }

    private ActivitySettingBinding binding;
    private List<String> statusList = new ArrayList<>();
    private RecyclerSettingListAdpter recyclerSettingListAdpter;
    private HttpAPI httpAPI;
    private StarCloudAPI starCloudAPI;
    private static ProgressBar progressBar;
    private static TextView progressText;
    private static WeakReference<SettingActivity> instance;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 讀取最後設定語言的設定
        // LanguageHelper.applySavedLanguage(this);
        binding = ActivitySettingBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        httpAPI = new HttpAPI(getHandlerMain());
        starCloudAPI = new StarCloudAPI(getHandlerMain(), getHandlerMain());
        instance = new WeakReference<>(this);
        progressBar = binding.progressBar;
        progressText = binding.progressText;

        recyclerSettingListAdpter = new RecyclerSettingListAdpter(statusList);
        binding.recyclerSettingList.setAdapter(recyclerSettingListAdpter);
        binding.recyclerSettingList
                .setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));

        MyApp.getInstance().initialSettingData();

        if (!MyApp.getInstance().getMachine().getMachineID().isEmpty()) {
            binding.editMachineID.setText(MyApp.getInstance().getMachine().getMachineID());
            binding.buttonReload.setText("重新綁定");
        }

        if ("prod".equals(MyApp.getInstance().getMachine().getMqttEnv())) {
            binding.radioProd.setChecked(true);
        } else {
            binding.radioDemo.setChecked(true);
        }

        if (statusList.isEmpty()) {
            SettinglogsDao settinglogsDao = new SettinglogsDao(this);
            for (String data : settinglogsDao.getAll()) {
                statusList.add(data);
            }
        }

        if (!statusList.isEmpty()) {
            recyclerSettingListAdpter.notifyItemInserted(statusList.size() - 1);
        }

        binding.buttonBack.setOnClickListener(v -> {
            MyApp.updateLog(getCtx());
            finish();
        });

        binding.buttonReload.setOnClickListener(v -> {
            if (binding.editMachineID.getText().length() <= 0) {
                getHandlerMain().start(getClass().getSimpleName(), "@機器序號未輸入");
                return;
            }

            // 開始綁定 → 顯示進度條
            // showLoading(true);
            binding.progressLayout.setVisibility(View.VISIBLE);
            VideoImageMixedPlayer.clearAdsCache(this);
            ImageGlide.clearProductCache(this);
            getLogs().info("刪除廣告與商品暫存檔");
            getHandlerMain().start("ButtonReloadOnClick", Option.DATA_RELOAD.getOption(), "data reload");
        });

        getTools().setImmHideByFocusChange(binding.editMachineID);
        binding.editMachineID.clearFocus();
    }

    public void saveStatusList(Context context) {
        SettinglogsDao settinglogsDao = new SettinglogsDao(context);
        settinglogsDao.deleteAll();
        settinglogsDao.insertAll(statusList);
        settinglogsDao.close();
    }

    public static void updateProgressUI(int percent, String message) {
        if (instance == null) return;
        SettingActivity activity = instance.get();
        if (activity == null)
            return;

        activity.runOnUiThread(() -> {
            if (activity.progressBar != null) {
                activity.progressBar.setProgress(percent);
            }
            if (activity.progressText != null) {
                activity.progressText.setText(message + " (" + percent + "%)");
            }
        });
    }

    private void checkSetting() {
        int size = statusList.size();
        statusList.clear();
        recyclerSettingListAdpter.notifyItemRangeRemoved(0, size);

        if (!MyApp.getInstance().getMachine().getMachineID().isEmpty()) {
            statusList.add("download maching data:"
                    + MyApp.getInstance().getMachine().getMachineID()
                    + "/"
                    + Tools.randomReplace(MyApp.getInstance().getMachine().getApiKey(), 0.3));
        }

        if (MyApp.getInstance().getGreenInvoice().getGreenMerchantID() != null) {
            statusList.add("download greenpay Invoice data:"
                    + Tools.randomReplace(String.valueOf(MyApp.getInstance().getGreenInvoice().getGreenMerchantID()),
                            0.3)
                    + "/"
                    + Tools.randomReplace(String.valueOf(MyApp.getInstance().getGreenInvoice().getGreenHashKey()), 0.3)
                    + "/"
                    + Tools.randomReplace(String.valueOf(MyApp.getInstance().getGreenInvoice().getGreenHashIV()), 0.3)
                    + "/"
                    + Tools.randomReplace(String.valueOf(MyApp.getInstance().getGreenInvoice().getGreenEmail()), 0.3));
        }

        if (!MyApp.getInstance().getEsunpay().getStoreID().isEmpty()) {
            statusList.add("download esunpay data:"
                    + Tools.randomReplace(MyApp.getInstance().getEsunpay().getStoreID(), 0.3)
                    + "/"
                    + Tools.randomReplace(MyApp.getInstance().getEsunpay().getTermID(), 0.3)
                    + "/"
                    + Tools.randomReplace(MyApp.getInstance().getEsunpay().getHash(), 0.3));
        }

        if (MyApp.getInstance().getGreenpaySetting().getAppKey() != null
                && !MyApp.getInstance().getGreenpaySetting().getAppKey().isEmpty()) {
            statusList.add("download greenpay data:"
                    + Tools.randomReplace(String.valueOf(MyApp.getInstance().getGreenpaySetting().getAppId()), 0.3)
                    + "/"
                    + Tools.randomReplace(MyApp.getInstance().getGreenpaySetting().getAppKey(), 0.3)
                    + "/"
                    + Tools.randomReplace(MyApp.getInstance().getGreenpaySetting().getPartnerKey(), 0.3));

            statusList.add("download greenpay merchant data:"
                    + Tools.randomReplace(String.valueOf(MyApp.getInstance().getGreenpayMerchant().getLineMerchantId()),
                            0.3)
                    + "/"
                    + Tools.randomReplace(MyApp.getInstance().getGreenpayMerchant().getPsMerchantId(), 0.3)
                    + "/"
                    + Tools.randomReplace(MyApp.getInstance().getGreenpayMerchant().getEasyMerchantId(), 0.3)
                    + "/"
                    + Tools.randomReplace(MyApp.getInstance().getGreenpayMerchant().getPiMerchantId(), 0.3)
                    + "/"
                    + Tools.randomReplace(MyApp.getInstance().getGreenpayMerchant().getJkoMerchantId(), 0.3));
        }

        if (!MyApp.getInstance().getProductList().isEmpty()) {
            size = MyApp.getInstance().getProductList().size();
            statusList.add("download product data:" + size);
        }

        if (!MyApp.getInstance().getFontendAdUrlString().isEmpty()) {
            size = MyApp.getInstance().getFontendAdUrlString().size();
            statusList.add("download ad url data:" + size);
        }

        recyclerSettingListAdpter.notifyItemInserted(statusList.size() - 1);

        updateProgressUI(100, "下載中...");
        binding.progressLayout.setVisibility(View.GONE);
    }
}