package com.unibuy.smartdevice.ui.dialog;

import android.content.Context;
import android.graphics.Color;

import com.unibuy.smartdevice.DialogAbstract;
import com.unibuy.smartdevice.MyApp;
import com.unibuy.smartdevice.controller.DevNFCPayController;
import com.unibuy.smartdevice.databinding.DialogCheckoutNfcRechargeBinding;
import com.unibuy.smartdevice.devices.DevNFCPay;
import com.unibuy.smartdevice.devices.SlotField;
import com.unibuy.smartdevice.exception.LogsEmptyException;
import com.unibuy.smartdevice.exception.LogsIOException;
import com.unibuy.smartdevice.exception.LogsParseException;
import com.unibuy.smartdevice.exception.LogsSettingEmptyException;
import com.unibuy.smartdevice.external.HttpAPI;
import com.unibuy.smartdevice.structure.BuyStructure;
import com.unibuy.smartdevice.structure.InvoiceItemStructure;
import com.unibuy.smartdevice.structure.ProductStructure;
import com.unibuy.smartdevice.structure.ReportFreeGiftCodeStructure;
import com.unibuy.smartdevice.tools.HandlerMain;
import com.unibuy.smartdevice.tools.HandlerMainCountdown;
import com.unibuy.smartdevice.tools.ToastHandlerMain;
import com.unibuy.smartdevice.ui.FontendActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

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

public class CheckoutNfcRechargeDialog extends DialogAbstract {
    public enum Option {
        TOAST(0),
        COUNTDOWN_CANCEL(1),
        SET_COUNTDOWN_TEXT(2),
        SET_COUNTDOWN_TEXT_AND_BTN_OPEN(3),
        SET_COUNTDOWN_TEXT_AND_BTN_CLOSE(4),
        RESPONSE(5),
        CHANGE_DISPATCH(6),
        CHANGE_BUY(7),
        REPORT_FLOW(8),
        POST_INVOICE(9),
        REPORT_INVOICE(10),
        ;

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

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

    @Override
    protected HandlerMain setHandlerMain() {
        return new ToastHandlerMain(getContext(), getLogs()) {
            @Override
            protected void execute(Context context, int commandCode, String message) {
                if (MyApp.getInstance().getBuyList().size() <= 0) {

                    dialogCancel();
                } else {
                    Option option = optionMap.get(commandCode);
                    getLogs().info("Option " + option.getOption() + ":" + option.name());
                    switch (option) {
                        case TOAST:
                            super.execute(context, commandCode, message);
                            break;
                        case COUNTDOWN_CANCEL:
                            cancelOnThreadCountdown();
                            break;
                        case SET_COUNTDOWN_TEXT:
                            setButtonCancelText(Integer.valueOf(message));
                            break;
                        case SET_COUNTDOWN_TEXT_AND_BTN_OPEN:
                            setButtonCancelText(Integer.valueOf(message));
                            buttonOpen();
                            break;
                        case SET_COUNTDOWN_TEXT_AND_BTN_CLOSE:
                            setButtonCancelText(Integer.valueOf(message));
                            buttonClose();
                            break;
                        case RESPONSE:
                            if (isResponse) {
                                if (!message.isEmpty()) {
                                    if (message.equals("0000")) {
                                        MyApp.getInstance().getReportFlowInfoData().setFlowStatusType(1);
                                        binding.textStatus.setText(DevNFCPay.recordMessage(message));
                                        try {
                                            httpAPI.reportFlowInfo(MyApp.getInstance().getReportFlowInfoData());
                                        } catch (LogsSettingEmptyException | LogsParseException e) {
                                            getLogs().warning(e);
                                        }
                                    } else {
                                        MyApp.getInstance().getReportFlowInfoData().setFlowStatusType(0);
                                        binding.textStatus.setText(DevNFCPay.recordMessage(message));
                                    }
                                } else {
                                    MyApp.getInstance().getReportFlowInfoData().setFlowStatusType(0);
                                    binding.textStatus.setText(DevNFCPay.recordMessage(message));
                                }

//                                binding.textStatus.setText(DevNFCPay.recordMessage(message));
//
//                                getHandler().postDelayed(new Runnable() {
//                                    @Override
//                                    public void run() {
//                                        try {
//                                            httpAPI.reportFlowInfo(MyApp.getInstance().getReportFlowInfoData());
//                                        } catch (LogsSettingEmptyException | LogsParseException e) {
//                                            getLogs().warning(e);
//                                        }
//                                    }
//                                }, 5000);

                                isResponse = false;
                            }
                            break;
                        case CHANGE_DISPATCH:
                            changeDispatch();
                            break;
                        case CHANGE_BUY:
                            changeBuy();
                            break;
                        case REPORT_FLOW:
                            getLogs().info(MyApp.getInstance().getReportFlowInfoData().toString());

//                            if (MyApp.getInstance().getReportFlowInfoData().getFlowStatusType() == 0) {
//                                changeBuy();
//                            } else {
                                if (!MyApp.getInstance().getReportFlowInfoData().getInvoiceInfo().isEmpty()) {
                                    try {
                                        httpAPI.postInvoiceByGreen(MyApp.getInstance().getPostInvoiceByGreenData());
                                    } catch (LogsSettingEmptyException | LogsParseException e) {
                                        getLogs().warning(e);
                                    }
                                }

                                changeDispatch();
//                            }
                            break;
                        case POST_INVOICE:
                            try {
                                httpAPI.postInvoiceByGreen(MyApp.getInstance().getPostInvoiceByGreenData());
                            } catch (LogsSettingEmptyException | LogsParseException e) {
                                getLogs().warning(e);
                            }
                            changeDispatch();
                            break;
                        case REPORT_INVOICE:
                            changeDispatch();
                            break;
                    }
                }
            }
        };
    }

    private DialogCheckoutNfcRechargeBinding binding;
    private CloseDialogOnThreadHandler closeDialogCountdown;
    private DevNFCPayController nfcPayController;
    private boolean isResponse;
    private boolean isChangeDispatch;
    private HttpAPI httpAPI;

    public CheckoutNfcRechargeDialog(Context context, HandlerMain srcHandlerMain) {
        super(context, srcHandlerMain);
    }

    @Override
    protected void onCreate(Context context) {
        binding = DialogCheckoutNfcRechargeBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        isResponse = true;
        isChangeDispatch = true;
        httpAPI = new HttpAPI(getHandlerMain());

        binding.buttonChange.setOnClickListener(v -> changeBuy());
        binding.buttonCancel.setOnClickListener(v -> dialogCancel());

        buttonClose();
        closeDialogCountdown = new CloseDialogOnThreadHandler(getHandlerMain());
        closeDialogCountdown.start(30);

        binding.textPrice.setText(String.valueOf(getTotalPrice()));

        binding.textStatus.setText("交易讀取中，請將卡片/手機停留片刻，\n勿快速移動，系統完成後會自動返回。");

        ProductStructure buyProduct = MyApp.getInstance().getBuyList().get(0).getProduct();
        MyApp.getInstance().getReportFlowInfoData().setProductId(buyProduct.getProductID());
        MyApp.getInstance().getReportFlowInfoData().setTotalPrice(getTotalPrice());
        JSONArray jsonArray = new JSONArray();

        try {
            MyApp.getInstance().getInvoiceItems().clear();
            for (BuyStructure buyData : MyApp.getInstance().getBuyList()) {
                JSONObject productData = new JSONObject();
                productData.put("pid", buyData.getProduct().getProductID());
                productData.put("amount", String.valueOf(buyData.getProduct().getRealPrice()));
                productData.put("num", String.valueOf(buyData.getCount()));
                jsonArray.put(productData);

                InvoiceItemStructure invoiceItem = new InvoiceItemStructure("", "", 0, "件", 0, 0);
                invoiceItem.setItemSeq(buyData.getProduct().getProductID());
                invoiceItem.setItemName(buyData.getProduct().getProductName());
                invoiceItem.setItemCount(buyData.getCount());
                invoiceItem.setItemPrice(buyData.getProduct().getRealPrice());
                invoiceItem.setItemAmount(buyData.getFullPrice());
                try {
                    SlotField slotField = SlotField.getSlotField(buyData.getField());
                    switch (slotField) {
                        case VMC:
                            invoiceItem.setItemWord("件");
                            break;
                        case ELECTRIC:
                            invoiceItem.setItemWord("時");
                            break;
                    }
                } catch (LogsEmptyException e) {
                    invoiceItem.setItemWord("件");
                }
                MyApp.getInstance().getInvoiceItems().add(invoiceItem);
            }
            MyApp.getInstance().getPostInvoiceByGreenData().setInvoiceItem(MyApp.getInstance().getInvoiceItems());
            MyApp.getInstance().getPostInvoiceByGreenData().setInvoiceData(MyApp.getInstance().getInvoiceData());
            MyApp.getInstance().getPostInvoiceByGreenData().setTotalPrice(getTotalPrice());
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
        MyApp.getInstance().getReportFlowInfoData().setShoppingCartInfoByJsonArray(jsonArray);

        try {
            nfcPayController = new DevNFCPayController(getHandlerMain());
            nfcPayController.start(2, getTotalPrice());
        } catch (LogsIOException e) {
            getLogs().warning(e);
            binding.textStatus.setText("刷卡機無法開啟");
            getHandlerMain().getHandler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    changeBuy();
                }
            }, 5000);
        }
        //payType 1:信用卡 2.卡片支付 4.手機支付
    }

    public void buttonClose() {
        this.binding.buttonChange.setEnabled(false);
        this.binding.buttonChange.setTextColor(Color.GRAY);
        this.binding.buttonCancel.setEnabled(false);
        this.binding.buttonCancel.setTextColor(Color.GRAY);
    }

    public void buttonOpen() {
        binding.buttonChange.setEnabled(true);
        binding.buttonChange.setTextColor(Color.BLACK);
        binding.buttonCancel.setEnabled(true);
        binding.buttonCancel.setTextColor(Color.BLACK);
    }

    public int getTotalPrice() {
        int totalPrice = 0;
        if (MyApp.getInstance().getBuyList().size() == 0) return totalPrice;
        for(BuyStructure buy: MyApp.getInstance().getBuyList()) {
            if (!buy.isFreeGift()) totalPrice += buy.getFullPrice();
        }
        if (MyApp.getInstance().getReportFreeGiftCodeStructure() != null) {
            switch (MyApp.getInstance().getReportFreeGiftCodeStructure().getMode()) {
                case 0:
                    break;
                case 1:
                    totalPrice = totalPrice - MyApp.getInstance().getReportFreeGiftCodeStructure().getDiscountAmount();
                    break;
                case 2:
                    totalPrice = (int) (totalPrice * MyApp.getInstance().getReportFreeGiftCodeStructure().getDiscountPercentage());
                    break;
            }
        }
        if (totalPrice == 0) totalPrice = 1;
        return totalPrice;
    }

    public void changeDispatch() {
        if (isChangeDispatch) {
            isChangeDispatch = false;
            if (nfcPayController != null) {
                nfcPayController.shutdown();
            }
            closeDialogCountdown.shutdown();
            changeDialog(DispatchDialog.class);
        }
    }

    public void changeBuy() {
        if (nfcPayController != null) {
            nfcPayController.shutdown();
        }
        closeDialogCountdown.shutdown();
        changeDialog(BuyDialog.class);
    }

    public void dialogCancel() {
        if (this.isShowing()) {
            MyApp.getInstance().setReportFreeGiftCodeStructure(new ReportFreeGiftCodeStructure("", 0, "", 0, 0, ""));
            getSrcHandlerMain().start(getClass().getSimpleName(), FontendActivity.Option.STOP_COUNTDOWN.getOption(), "");
            if (nfcPayController != null) {
                nfcPayController.shutdown();
            }
            closeDialogCountdown.shutdown();
            MyApp.getInstance().getBuyList().clear();
            cancel();
        }
    }

    public void cancelOnThreadCountdown() {
        if (nfcPayController != null) {
            nfcPayController.shutdown();
        }
        MyApp.getInstance().getBuyList().clear();
        cancel();
    }


    public void setButtonCancelText(long countdown) {
        binding.buttonCancel.setText("取消("+countdown+")");
    }

    public class CloseDialogOnThreadHandler extends HandlerMainCountdown {
        public CloseDialogOnThreadHandler(HandlerMain handlerMain) {
            super(handlerMain);
        }

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

        @Override
        protected void close(HandlerMain handlerMain) {
            // 安全判斷，避免 dialog 已經被關閉後再次 cancel 造成錯誤
            if (CheckoutNfcRechargeDialog.this.isShowing()) {
                handlerMain.start(getClass().getSimpleName(), Option.COUNTDOWN_CANCEL.getOption(), "40");
            }
        }

        @Override
        protected void execute(long countdown, HandlerMain handlerMain) {
//            if (countdown < 5) {
//                handlerMain.start(getClass().getSimpleName(), Option.SET_COUNTDOWN_TEXT_AND_BTN_OPEN.getOption(), String.valueOf(countdown));
//            } else {
                handlerMain.start(getClass().getSimpleName(), Option.SET_COUNTDOWN_TEXT.getOption(), String.valueOf(countdown));
//            }
        }

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