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.List;

import kz.com.aman.kassa.bank.gui.CustomKeyBoardDilalog;
import ru.m4bank.mpos.library.external.transactions.CardReadingCallbackHandler;
import ru.m4bank.mpos.service.commons.utils.ArrayUtils;
import ru.m4bank.mpos.service.data.dynamic.objects.Reader;
import ru.m4bank.mpos.service.hardware.error.ErrorHandler;
import ru.m4bank.mpos.service.hardware.external.cardreaderlib.data.ApplicationIdConv;
import ru.m4bank.mpos.service.result.Result;
import ru.m4bank.mpos.service.transactions.data.SimpleCardTransactionData;
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 timber.log.Timber;

public class CardReadingCallbackHandlerImpl implements CardReadingCallbackHandler<Result> {
    private final M4BankActivity activity;
    private CustomKeyBoardDilalog customKeyBoardDilalog;

    public CardReadingCallbackHandlerImpl(M4BankActivity activity) {
        this.activity = activity;
        customKeyBoardDilalog = new CustomKeyBoardDilalog();
    }

    @Override
    public void onDeviceToConnectSelectionRequested(List<String> 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 onCardReaderForTransactionGettingCompleted() {
        Timber.d("Reader has been received");
    }

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

    @Override
    public void onDeviceToUseSelectionRequested(List<Reader> 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, ArrayUtils.newArrayList(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);
            builder.create().show();
        });
    }

    @Override
    public void onCompleted(Result result) {
        activity.runOnUiThread(() -> Toast.makeText(activity, result.getResultType() + " " + 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 onTransactionInit() {

    }

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

    @Override
    public void onError(ErrorHandler errorHandler, TransactionErrorData errorData) {
        activity.runOnUiThread(() -> Toast.makeText(activity, errorHandler.getFinalDescription(), Toast.LENGTH_LONG).show());
    }

    @Override
    public void onErrorWithPossibilityToRetry(ErrorHandler errorHandler) {
        activity.runOnUiThread(() -> Toast.makeText(activity, errorHandler.getFinalDescription(), Toast.LENGTH_LONG).show());
        activity.getClientInterface().getTransactionManager().tryToRepeatExecuteLastRequestInTransaction();
    }

    @Override
    public void onTransactionDataReceivedError(TransactionData data) {

    }

    @Override
    public void onUserInformationRequested(boolean signNeeded) {
        activity.getClientInterface()
                .getTransactionManager()
                .sendTransactionUserData("signature", "phone", "vsa@centercorptech.net");
    }

    @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 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 onConnectingProcessStarted(String deviceName) {
        Timber.d("Connecting process started");
    }

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

    }

    @Override
    public void onRepeat(int attemptNumber) {
        activity.runOnUiThread(() -> Toast.makeText(activity, "Repeat attempt number " + attemptNumber, Toast.LENGTH_SHORT).show());
    }

    @Override
    public void onReceiveCommonCardData(SimpleCardTransactionData simpleCardTransactionData) {
        String pan = simpleCardTransactionData.getCardNumber();
        String expDate = simpleCardTransactionData.getCardExpiryDate();
        String cardHolderName = simpleCardTransactionData.getCardHolderName();
        activity.runOnUiThread(() -> Toast.makeText(activity, "card data: " + pan + " - " + expDate + " - " + cardHolderName, Toast.LENGTH_SHORT).show());
    }

    @Override
    public void onRequiredApplicationSelection(List<ApplicationIdConv> applicationOfList) {
        //        activity.runOnUiThread(() -> {
        //            AlertDialog.Builder builder = new AlertDialog.Builder(activity);
        //            builder.setTitle("Choose application identifier");
        //
        //            Spinner deviceListSpinner = new Spinner(activity);
        //            ArrayAdapter<String> adapter = new ArrayAdapter<>(activity, android.R.layout.simple_spinner_item, applicationOfList);
        //            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //            deviceListSpinner.setAdapter(adapter);
        //
        //            builder.setPositiveButton("OK", (dialog, which) -> {
        //                activity.getClientInterface()
        //                        .getTransactionManager()
        //                        .setTransactionApplicationIdentifier(deviceListSpinner.getSelectedItem().toString());
        //                dialog.dismiss();
        //            });
        //
        //            builder.setView(deviceListSpinner);
        //            builder.create().show();
        //        });
    }
}
