package com.unibuy.smartdevice.ui.dialog;

import android.content.Context;

import com.unibuy.smartdevice.DialogAbstract;
import com.unibuy.smartdevice.MyApp;
import com.unibuy.smartdevice.R;
import com.unibuy.smartdevice.databinding.DialogCheckoutEsunPayBinding;
import com.unibuy.smartdevice.databinding.DialogCheckoutLinePayBinding;
import com.unibuy.smartdevice.devices.DeviceType;
import com.unibuy.smartdevice.devices.SlotField;
import com.unibuy.smartdevice.devices.UsbDev;
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.exception.LogsUnsupportedOperationException;
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.HandlerMainScheduler;
import com.unibuy.smartdevice.tools.ToastHandlerMain;
import com.unibuy.smartdevice.tools.Tools;
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 CheckoutLinePayDialog extends DialogAbstract {
    public enum Option {
        TOAST(0),
        COUNTDOWN_CANCEL(1),
        SET_COUNTDOWN_TEXT(2),
        TRANSACTION_SUCCESSFUL(4),
        TRANSACTION_FAILED(5),
        CHANGE_DISPATCH(6),
        CHANGE_BUY(7),
        REPORT_FLOW(8),
        POST_INVOICE(9),
        REPORT_INVOICE(10),
        SET_STATUS_TEXT(11),
        ;

        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(getCtx(), 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 TRANSACTION_SUCCESSFUL:
                            if (isTransaction) {
                                MyApp.getInstance().getReportFlowInfoData().setFlowStatusType(1);
                                try {
                                    httpAPI.reportFlowInfo(MyApp.getInstance().getReportFlowInfoData());
                                } catch (LogsSettingEmptyException | LogsParseException e) {
//                                    exception(context, e.getErrorCode(), e.getLocalizedMessage());
                                    getLogs().warning(e);
                                }
                                isTransaction = false;
                            }
                            break;
                        case TRANSACTION_FAILED:
                            if (isTransaction) {
                                MyApp.getInstance().getReportFlowInfoData().setFlowStatusType(0);
                                try {
                                    httpAPI.reportFlowInfo(MyApp.getInstance().getReportFlowInfoData());
                                } catch (LogsSettingEmptyException | LogsParseException e) {
//                                    exception(context, e.getErrorCode(), e.getLocalizedMessage());
                                    getLogs().warning(e);
                                }
                                isTransaction = 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) {
                                start(getSrcClassName(), "@"+getContext().getString(R.string.transaction_failure));//交易失敗
                                start(getSrcClassName(), CashPayDialog.Option.CHANGE_BUY.getOption(), "change buy");
                            } else {
                                if (MyApp.getInstance().getReportFlowInfoData().getInvoiceInfo().isEmpty()) {
                                    start(getSrcClassName(), CashPayDialog.Option.CHANGE_DISPATCH.getOption(), "change dispatch");
                                } else {
                                    start(getSrcClassName(), CashPayDialog.Option.POST_INVOICE.getOption(), "post invoice");
                                }
                            }
                            break;
                        case POST_INVOICE:
                            try {
                                httpAPI.postInvoiceByGreen(MyApp.getInstance().getPostInvoiceByGreenData());
                            } catch (LogsSettingEmptyException | LogsParseException e) {
//                                exception(context, e.getErrorCode(), e.getLocalizedMessage());
                                getLogs().warning(e);
                            }
                            start(getSrcClassName(), Option.CHANGE_DISPATCH.getOption(), "change dispatch");
                            break;
                        case REPORT_INVOICE:
                            start(getSrcClassName(), Option.CHANGE_DISPATCH.getOption(), "change dispatch");
                            break;
                        case SET_STATUS_TEXT:
                            binding.textStatus.setText(message);
                            break;
                    }
                }
            }
        };
    }

    private DialogCheckoutLinePayBinding binding;
    private CloseDialogOnThreadHandler closeDialogCountdown;
    private boolean openBarcode;
    private ReadBarCodeOnScheduler readBarCodeOnScheduler;
    private boolean isTransaction;
    private boolean isChangeDispatch;
    private HttpAPI httpAPI;

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

    @Override
    protected void onCreate(Context context) {
        binding = DialogCheckoutLinePayBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        openBarcode = true;
        isTransaction = true;
        isChangeDispatch = true;
        httpAPI = new HttpAPI(getHandlerMain());

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

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

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

        ProductStructure buyProduct = MyApp.getInstance().getBuyList().get(0).getProduct();
        MyApp.getInstance().getReportFlowInfoData().setProductId(buyProduct.getProductID());
        MyApp.getInstance().getReportFlowInfoData().setTotalPrice(getTotalPrice());
        JSONArray jsonArray = new JSONArray();
        try {
            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);


        readBarCodeOnScheduler = new ReadBarCodeOnScheduler(getHandlerMain());
        readBarCodeOnScheduler.start();
    }

    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) {
            closeDialogCountdown.shutdown();
            openBarcode = false;
            isChangeDispatch = false;
            changeDialog(DispatchDialog.class);
        }
    }

    public void changeBuy() {
        openBarcode = false;
        closeDialogCountdown.shutdown();
        changeDialog(BuyDialog.class);
    }

    public void dialogCancel() {
        MyApp.getInstance().setReportFreeGiftCodeStructure(new ReportFreeGiftCodeStructure("", 0, "", 0, 0, ""));
        getSrcHandlerMain().start(getClass().getSimpleName(), FontendActivity.Option.STOP_COUNTDOWN.getOption(), "");
        openBarcode = false;
        readBarCodeOnScheduler.setRun(false);
        closeDialogCountdown.shutdown();
        MyApp.getInstance().getBuyList().clear();
        cancel();
    }

    public void cancelOnThreadCountdown() {
        openBarcode = false;
        MyApp.getInstance().getBuyList().clear();
        cancel();
    }

    public void setButtonCancelText(long countdown) {
        binding.buttonCancel.setText(getCtx().getString(R.string.cancel)+"("+countdown+")");
    }

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

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

        @Override
        protected void execute(HandlerMain handlerMain) {
            try {
                int totalPrice = 0;
                for (BuyStructure buy : MyApp.getInstance().getBuyList()) {
                    totalPrice += buy.getFullPrice();
                }

                UsbDev usbDev = new UsbDev(DeviceType.QRCODE_SCANNER);
                byte[] buffer = new byte[1000];
                usbDev.read(buffer, 100);
                for (int i=0; i<7; i++) {
                    if (isRun() && openBarcode) {
                        int size = usbDev.read(buffer, 5000);
                        if (size > 5) {
                            String barCodeString = new String(buffer, 0, size);
                            if (barCodeString.length() > 18)
                                barCodeString = barCodeString.trim();
                            if (barCodeString.length() == 18) {
                                getHandlerMain().start(getLogs().getClassName(), Option.SET_STATUS_TEXT.getOption(), getCtx().getString(R.string.receive_barcode)+"：" + Tools.randomReplace(barCodeString, 0.3) + "，"+getCtx().getString(R.string.send_transaction));//收到條碼,送出交易
                                try {
                                    httpAPI.linepay(barCodeString, totalPrice);
                                } catch (LogsSettingEmptyException | LogsParseException e) {
                                    getLogs().warning(e);
                                }

                                openBarcode = false;
                            } else {
                                getHandlerMain().start(getLogs().getClassName(), Option.SET_STATUS_TEXT.getOption(), getCtx().getString(R.string.barcode_error_change_barcode_code_length)+barCodeString.length());//條碼錯誤，請更換條碼:碼長
                            }
                        }
                    }
                }
                usbDev.closePort();
            } catch (LogsUnsupportedOperationException | LogsIOException | LogsEmptyException e) {
                getLogs().warning(e);
            }
        }

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

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