package com.unibuy.smartdevice.ui.dialog;

import android.content.Context;
import android.view.View;

import androidx.recyclerview.widget.LinearLayoutManager;

import com.unibuy.smartdevice.DialogAbstract;
import com.unibuy.smartdevice.MyApp;
import com.unibuy.smartdevice.databinding.DialogPickupCodeBuyBinding;
import com.unibuy.smartdevice.devices.SlotField;
import com.unibuy.smartdevice.exception.LogsEmptyException;
import com.unibuy.smartdevice.structure.BuyStructure;
import com.unibuy.smartdevice.tools.HandlerMain;
import com.unibuy.smartdevice.tools.HandlerMainCountdown;
import com.unibuy.smartdevice.tools.ToastHandlerMain;
import com.unibuy.smartdevice.tools.Tools;
import com.unibuy.smartdevice.ui.recycler.RecyclerDialogPickupCodeBuyListAdpter;

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

public class BuyPickupCodeDialog extends DialogAbstract {
    public enum Option {
        TOAST(0),
        COUNTDOWN_CANCEL(1),
        SET_COUNTDOWN_TEXT(2),
        SET_PRICE(3),
        RESET_COUNTDOWM(4),
        RESET_COUNTDOWM_TOAST(5),
        ;

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

                    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_PRICE:
                                binding.textPrice.setText(String.valueOf(getTotalPrice()));
                                closeDialogCountdown.setCountdown(40);
                            break;
                        case RESET_COUNTDOWM:
                                closeDialogCountdown.setCountdown(40);
                            break;
                        case RESET_COUNTDOWM_TOAST:
                                super.execute(context, commandCode, message);
                                closeDialogCountdown.setCountdown(40);
                            break;
                    }
                }
            }
        };
    }

    private DialogPickupCodeBuyBinding binding;
    private RecyclerDialogPickupCodeBuyListAdpter recyclerDialogPickupCodeBuyListAdpter;
    private CloseDialogOnThreadHandler closeDialogCountdown;
    private boolean isChangeDispatch;

    public BuyPickupCodeDialog(Context context, HandlerMain srcHandlerMain) {
        super(context, srcHandlerMain);
        getLogs().info("open:" + getClass().getSimpleName());
    }

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

        isChangeDispatch = true;

        this.recyclerDialogPickupCodeBuyListAdpter = new RecyclerDialogPickupCodeBuyListAdpter(getCtx(), MyApp.getInstance().getBuyList(), getHandlerMain());
        this.binding.recyclerDialogBuyList.setAdapter(recyclerDialogPickupCodeBuyListAdpter);
        this.binding.recyclerDialogBuyList.setLayoutManager(new LinearLayoutManager(context));

        MyApp.getInstance().getReportFlowInfoData().setOrderId(Tools.generateTimeBasedUUID());
        MyApp.getInstance().getReportFlowInfoData().setFlowType(6);
        MyApp.getInstance().getPostInvoiceByGreenData().setOrderId(MyApp.getInstance().getReportFlowInfoData().getOrderId());

        this.binding.layoutMemberTransactions.setVisibility(View.GONE);

        this.binding.buttonGetProduct.setOnClickListener(v -> gotoGetProduct());
        this.binding.buttonCancel.setOnClickListener(v -> dialogCancel());

        closeDialogCountdown = new CloseDialogOnThreadHandler(getHandlerMain());
        closeDialogCountdown.start(40);

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

    public int getTotalPrice() {
        int totalPrice = 0;
        if (MyApp.getInstance().getBuyList().size() == 0) return totalPrice;
        for(BuyStructure buy: MyApp.getInstance().getBuyList()) {
            totalPrice += buy.getFullPrice();
        }
        return totalPrice;
    }

    public void gotoGetProduct() {
        if (isChangeDispatch) {
            closeDialogCountdown.shutdown();
            isChangeDispatch = false;
            changeDialog(DispatchDialog.class);
            cancel();
        }
    }

    public void dialogCancel() {
        closeDialogCountdown.shutdown();
        int buyListSize = MyApp.getInstance().getBuyList().size();
        MyApp.getInstance().getBuyList().clear();
        if (buyListSize > 0) {
            recyclerDialogPickupCodeBuyListAdpter.notifyItemRangeRemoved(0, buyListSize);
        }
        cancel();
    }

    public void cancelOnThreadCountdown() {
        int buyListSize = MyApp.getInstance().getBuyList().size();
        MyApp.getInstance().getBuyList().clear();
        if (buyListSize > 0) {
            recyclerDialogPickupCodeBuyListAdpter.notifyItemRangeRemoved(0, buyListSize);
        }
        getTools().dialogClose();
        cancel();
    }

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

    public void gotoDialog() {
        closeDialogCountdown.shutdown();
        int flowType = MyApp.getInstance().getReportFlowInfoData().getFlowType();
        if (flowType == 5) {
            changeCheckout();
        } else {
            if (MyApp.getInstance().getDevSet().isShoppingCar()) {
                if (MyApp.getInstance().getDevSet().isInvoice()) {
                    changeDialog(InvoiceBarcodeDialog.class);
                } else {
                    changeCheckout();
                }
            } else {
                if (MyApp.getInstance().getDevSet().isInvoice()) {
                    BuyStructure buyData = MyApp.getInstance().getBuyList().get(0);
                    try {
                        SlotField slotField = SlotField.getSlotField(buyData.getField());
                        if (slotField.isInvoice()) {
                            changeDialog(InvoiceBarcodeDialog.class);
                        } else {
                            changeCheckout();
                        }
                    } catch (LogsEmptyException e) {
                        changeDialog(InvoiceBarcodeDialog.class);
                    }
                } else {
                    changeCheckout();
                }
            }
        }
    }

    public void changeCheckout() {
        closeDialogCountdown.shutdown();
        int flowType = MyApp.getInstance().getReportFlowInfoData().getFlowType();
        switch (flowType) {
            case 1:
                changeDialog(CheckoutNfcCardDialog.class);
                break;
            case 2:
                changeDialog(CheckoutNfcRechargeDialog.class);
                break;
            case 3:
                changeDialog(CheckoutEsunPayDialog.class);
                break;
            case 4:
                changeDialog(CheckoutNfcPhoneDialog.class);
                break;
            case 5:
                changeDialog(CheckoutAccessCodeDialog.class);
                break;
            case 9:
                changeDialog(CheckoutCashDialog.class);
                break;
            case 70:
                changeDialog(CheckoutLinePayDialog.class);
                break;
        }
    }


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

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

        @Override
        protected void close(HandlerMain handlerMain) {
            handlerMain.start(getClass().getSimpleName(), Option.COUNTDOWN_CANCEL.getOption(), "close dialog");
        }

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

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