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.LastReversalCardPaymentCallbackHandler;
import ru.m4bank.mpos.service.commons.data.ResultType;
import ru.m4bank.mpos.service.data.FiscalStatusData;
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.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 RevertCurrentOperationCallbackHandlerImpl implements LastReversalCardPaymentCallbackHandler<Result> {

    private final M4BankActivity activity;

    public RevertCurrentOperationCallbackHandlerImpl(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() {

    }

    @Override
    public void onNoBoundedDevicesFound() {

    }

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

    }

    @Override
    public void onRequiredReversal(String description, ResultCode resultCode) {

    }

    @Override
    public void onRequiredApplicationSelection(List applicationOfList) {

    }

    @Override
    public void onPrinterForRegistrationGettingCompleted() {

    }

    @Override
    public void onNoBoundedPrinterFound() {

    }

    @Override
    public void onTransactionDetailsReceived(Transaction transaction) {

    }

    @Override
    public void onSuccessStatusTransaction(Transaction transaction) {

    }

    @Override
    public void onErrorStatusTransaction() {

    }

    @Override
    public void onRequestedReportZ() {

    }

    @Override
    public void onCompletedPrinting(PrinterResult printerResult) {

    }

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

    }

    @Override
    public void onUserInformationRequested(boolean signNeeded) {

    }

    @Override
    public void onError(ErrorHandler errorHandler, TransactionErrorData transactionErrorData) {

    }

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

    @Override
    public void onTransactionDataReceivedError(TransactionData data) {

    }

    @Override
    public void onTransactionDataReceived(TransactionData data) {

    }

    @Override
    public void onTransactionCompleted() {

    }

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

    }
}
