package kz.com.aman.kassa.bank;

import android.app.AlertDialog;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

import ru.m4bank.mpos.library.external.transactions.EasyReversalCardCallbackHandler;
import ru.m4bank.mpos.library.external.transactions.GetTransactionsListCallbackHandler;
import ru.m4bank.mpos.service.commons.data.ResultType;
import ru.m4bank.mpos.service.data.FiscalStatusData;
import ru.m4bank.mpos.service.data.PrinterBaseData;
import ru.m4bank.mpos.service.data.PrinterErrorData;
import ru.m4bank.mpos.service.data.dynamic.objects.Reader;
import ru.m4bank.mpos.service.data.dynamic.objects.Transaction;
import ru.m4bank.mpos.service.data.dynamic.objects.result.ResultCode;
import ru.m4bank.mpos.service.hardware.error.ErrorHandler;
import ru.m4bank.mpos.service.hardware.external.cardreaderlib.data.ApplicationIdConv;
import ru.m4bank.mpos.service.hardware.external.cardreaderlib.data.enums.VirtualKeyboardStyleTypeConv;
import ru.m4bank.mpos.service.result.PrinterResult;
import ru.m4bank.mpos.service.result.Result;
import ru.m4bank.mpos.service.transactions.data.MessageButtonData;
import ru.m4bank.mpos.service.transactions.data.TransactionData;
import ru.m4bank.mpos.service.transactions.data.TransactionExecutionStatus;
import ru.m4bank.mpos.service.transactions.data.error.TransactionErrorData;
import ru.m4bank.mpos.service.transactions.dto.OnlineCardDataDto;
import timber.log.Timber;

public class EasyCardReversalCallbackHandlerImpl implements EasyReversalCardCallbackHandler<Result>, GetTransactionsListCallbackHandler<Result> {

    private final M4BankActivity activity;
    private Transaction transaction;

    public EasyCardReversalCallbackHandlerImpl(M4BankActivity activity) {
        this.activity = activity;
    }

    @Override
    public void notAuthorized() {
        activity.runOnUiThread(() -> Toast.makeText(activity, "Not authorized", Toast.LENGTH_SHORT).show());
    }

    @Override
    public void onCompleted(Result result) {
        activity.runOnUiThread(() -> Toast.makeText(activity, result.getResultType() + " " + (result.getDescription() == null ? "" : result.getDescription()), Toast.LENGTH_SHORT)
                .show());
    }

    @Override
    public void onWrongApiCalled() {
        activity.runOnUiThread(() -> Toast.makeText(activity, "Wrong method has been called", Toast.LENGTH_SHORT).show());
    }

    @Override
    public void onCardReaderForTransactionGettingCompleted() {
        Timber.d("Reader has been received");
    }

    @Override
    public void onNoBoundedDevicesFound() {
        Timber.d("No bounded readers");
    }

    @Override
    public void onConnectingProcessStarted(String deviceName) {

    }

    @Override
    public void onDisconnectedEventReceivedOrCanNotEstablishConnection(boolean reconnectAvailable, String description) {
        if (reconnectAvailable) {
            activity.runOnUiThread(() -> {
                AlertDialog.Builder builder = new AlertDialog.Builder(activity);
                builder.setMessage("Connection to cardreader has been lost, try to reconnect and repeat last operation?");
                builder.setCancelable(false);
                builder.setPositiveButton("Yes", (dialog, which) -> activity.getClientInterface().tryToReconnectAndRepeatLast());
                builder.setNegativeButton("No", (dialog, which) -> activity.getClientInterface().cancel());
                builder.create().show();
            });
        }
    }

    @Override
    public void onDeviceToConnectSelectionRequested(List deviceList) {
        activity.runOnUiThread(() -> {
            AlertDialog.Builder builder = new AlertDialog.Builder(activity);
            builder.setTitle("Choose device");

            Spinner deviceListSpinner = new Spinner(activity);
            ArrayAdapter<String> adapter = new ArrayAdapter<>(activity, android.R.layout.simple_spinner_item, deviceList);
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            deviceListSpinner.setAdapter(adapter);

            builder.setPositiveButton("OK", (dialog, which) -> {
                activity.getClientInterface()
                        .getTransactionManager()
                        .selectCardReader(deviceListSpinner.getSelectedItem().toString());
                dialog.dismiss();
            });

            builder.setView(deviceListSpinner);
            builder.create().show();
        });
    }

    @Override
    public void onWorkFlowDataRequested() {

    }

    @Override
    public void onReceiveCardData(OnlineCardDataDto data, boolean shouldConfirmBeManuallyCalled) {
        if (shouldConfirmBeManuallyCalled) {
            activity.getClientInterface().getTransactionManager().processOnlineTransaction(false);
        }
    }

    @Override
    public void onRequiredReversal(String description, ResultCode resultCode) {
        activity.runOnUiThread(() -> Toast.makeText(activity, "onRequiredReversal", Toast.LENGTH_LONG)
                .show());
    }

    @Override
    public void onRequiredApplicationSelection(List<ApplicationIdConv> list) {

    }

    @Override
    public void onPrinterForRegistrationGettingCompleted() {

    }

    @Override
    public void onNoBoundedPrinterFound() {

    }

    @Override
    public void onTransactionDetailsReceived(Transaction transaction) {
        activity.runOnUiThread(() -> Toast.makeText(activity, "onTransactionDetailsReceived", Toast.LENGTH_LONG)
                .show());
    }

    @Override
    public void onSuccessStatusTransaction(Transaction transaction) {
        activity.runOnUiThread(() -> Toast.makeText(activity, "onSuccessStatusTransaction", Toast.LENGTH_LONG)
                .show());
    }

    @Override
    public void onErrorStatusTransaction() {
        activity.runOnUiThread(() -> Toast.makeText(activity, "onErrorStatusTransaction", Toast.LENGTH_LONG)
                .show());
    }

    @Override
    public void onRequestedReportZ() {

    }

    @Override
    public void onCompletedPrinting(PrinterResult<PrinterErrorData, PrinterBaseData> printerErrorDataPrinterBaseDataPrinterResult) {

    }

    @Override
    public void onStatusFiscalModule(FiscalStatusData fiscalStatusData) {

    }

    @Override
    public void onReconciliationRequiredToProcess() {
        Timber.d("Reconciliation required!!!");
        activity.getClientInterface().getTransactionManager().makeReconciliationDuringTransaction();
    }

    @Override
    public void onReconciliationCompleted(Result result) {
        Timber.d("Reconciliation completed!!!");
        if (result.getResultType() == ResultType.SUCCESSFUL) {
            activity.getClientInterface().getTransactionManager().continueTransactionAfterReconciliation();
        } else {
            activity.runOnUiThread(() -> Toast.makeText(activity, "Reconciliation failed " + (result.getDescription() == null ? "" : result.getDescription()), Toast.LENGTH_LONG)
                    .show());
        }
    }

    @Override
    public void onRepeat(int attemptNumber) {

    }

    @Override
    public void onTransactionAmountRequested() {

    }

    @Override
    public void onTransactionDataRequested() {

    }

    @Override
    public void onDeviceToUseSelectionRequested(List deviceList) {
        activity.runOnUiThread(() -> {
            AlertDialog.Builder builder = new AlertDialog.Builder(activity);
            builder.setTitle("Choose device");

            Spinner deviceListSpinner = new Spinner(activity);
            ArrayAdapter<Reader> adapter = new ArrayAdapter<>(activity, android.R.layout.simple_spinner_item, new ArrayList<>(deviceList));
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            deviceListSpinner.setAdapter(adapter);

            builder.setPositiveButton("OK", (dialog, which) -> {
                activity.getClientInterface()
                        .getTransactionManager()
                        .setCardReaderToUse((Reader) deviceListSpinner.getSelectedItem());
                dialog.dismiss();
            });

            builder.setView(deviceListSpinner);
            activity.runOnUiThread(() -> builder.create().show());
        });
    }

    @Override
    public void onPrinterToUseSelectionRequested(List printerList) {

    }

    @Override
    public void onTransactionInit() {

    }

    @Override
    public void onTransactionExecutionStatusChanged(TransactionExecutionStatus newStatus) {
        activity.runOnUiThread(() -> Toast.makeText(activity, newStatus.name(), Toast.LENGTH_SHORT).show());
    }

    @Override
    public void onUserInformationRequested(boolean signNeeded) {

    }

    @Override
    public void onError(ErrorHandler errorHandler, TransactionErrorData transactionErrorData) {
        if (errorHandler.getCode() != null && errorHandler.getDescription() != null) {
            activity.runOnUiThread(() -> Toast.makeText(activity, "Error Code: " + errorHandler.getCode() + " error Description: "
                    + errorHandler.getDescription(), Toast.LENGTH_LONG)
                    .show());
        } else {
            activity.runOnUiThread(() -> Toast.makeText(activity, errorHandler.getServerCode() + " "
                    + errorHandler.getServerDescription(), Toast.LENGTH_LONG)
                    .show());
        }
    }

    @Override
    public void onErrorWithPossibilityToRetry(ErrorHandler errorHandler) {
        activity.getClientInterface().getTransactionManager().tryToRepeatExecuteLastRequestInTransaction();
    }

    @Override
    public void onTransactionDataReceivedError(TransactionData data) {
        activity.runOnUiThread(() -> Toast.makeText(activity, "onTransactionDataReceivedError", Toast.LENGTH_LONG)
                .show());
    }

    @Override
    public void onTransactionDataReceived(TransactionData data) {
        activity.runOnUiThread(() -> Toast.makeText(activity, "Transaction data has been received", Toast.LENGTH_LONG)
                .show());
    }

    @Override
    public void onTransactionCompleted() {
        activity.runOnUiThread(() -> Toast.makeText(activity, "Operation has been successfully completed", Toast.LENGTH_LONG)
                .show());
    }

    @Override
    public void onReconnectNeededToProcess() {
        activity.runOnUiThread(() -> {
            AlertDialog.Builder builder = new AlertDialog.Builder(activity);
            builder.setMessage("Connection to cardreader has been lost, try to reconnect and continue?");
            builder.setCancelable(false);
            builder.setPositiveButton("Yes", (dialog, which) -> activity.getClientInterface().getTransactionManager().tryToReconnectToCardReader());
            builder.setNegativeButton("No", (dialog, which) -> activity.getClientInterface().cancel());
            builder.create().show();
        });
    }

    @Override
    public void onWrongTerminal() {

    }

    @Override
    public void onSelectTransaction() {
        activity.getClientInterface().getTransactionManager().selectTransaction(transaction);
    }

    @Override
    public void onTransactionsListReceived(List<Transaction> transactionList) {
        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
        builder.setTitle("Choose transaction");

        Spinner transactionListSpinner = new Spinner(activity);
        ArrayAdapter<Transaction> adapter = new ArrayAdapter<>(activity, android.R.layout.simple_spinner_item, new ArrayList<>(transactionList));
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        transactionListSpinner.setAdapter(adapter);

        builder.setPositiveButton("OK", (dialog, which) -> {
            transaction = (Transaction) transactionListSpinner.getSelectedItem();
            activity.getClientInterface().getTransactionManager().makeCardReversal(this);
            dialog.dismiss();
        });

        builder.setView(transactionListSpinner);
        activity.runOnUiThread(() -> builder.create().show());
    }

    @Override
    public void onTransactionSelectionRequested(List<Transaction> transactionList) {

    }

    @Override
    public void onActivityUpdateUiThread() {

    }

    @Override
    public void onCreatePinPadButtons() {

    }

    @Override
    public void onShowPinPadKeyBoard(MessageButtonData messageButtonData) {

    }

    @Override
    public void onUpdateElementPin(int i) {

    }

    @Override
    public void onCloseKeyboard() {

    }

    @Override
    public void onRequiredAdditionalVirtualKeyboardSettings(VirtualKeyboardStyleTypeConv virtualKeyboardStyleTypeConv) {
        activity.showSelectStyleDialog(additionalData ->
                activity.getClientInterface().getTransactionManager().addVirtualPinKeyboardData(additionalData));
    }
}