package kz.com.aman.kassa.bank;

import android.widget.Toast;

import java.util.List;

import ru.m4bank.mpos.library.M4BankMposClientInterfaceFacade;
import ru.m4bank.mpos.library.external.transactions.XReportCallbackHandler;
import ru.m4bank.mpos.service.commons.data.ResultType;
import ru.m4bank.mpos.service.data.dynamic.objects.Transaction;
import ru.m4bank.mpos.service.hardware.printer.dto.data.PrintingType;
import ru.m4bank.mpos.service.result.Result;
import ru.m4bank.mpos.service.transactions.data.external.ExternalReconciliationData;

public class XReportCallbackHandlerImpl implements XReportCallbackHandler<Result> {

    private PrintingType reportType;
    private M4BankActivity activity;
    private M4BankMposClientInterfaceFacade clientInterface;

    public XReportCallbackHandlerImpl(M4BankMposClientInterfaceFacade clientInterface, PrintingType reportType, M4BankActivity activity) {
        this.reportType = reportType;
        this.activity = activity;
        this.clientInterface = clientInterface;
    }

    @Override
    public void onTransactionsListReceived(List<Transaction> list) {
        if(list == null || list.isEmpty()) {
            activity.runOnUiThread(() -> Toast.makeText(activity, "list of transaction is empty", Toast.LENGTH_SHORT).show());
        } else {
            ExternalReconciliationData data = new ExternalReconciliationData.Builder()
                    .reconciliationData(new ReconciliationPrinterDataBuilder().build(list, false))
                    .build();
            printReport(clientInterface, reportType, data);
        }
    }

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

    @Override
    public void onCompleted(Result result) {
        if(result == null || result.getResultType() != ResultType.SUCCESSFUL) {
            activity.runOnUiThread(() -> Toast.makeText(activity, "Wrong method has been called", Toast.LENGTH_SHORT).show());
        }else if(result.getResultType() == ResultType.SUCCESSFUL){
            // if code is successful and list is empty -> reconciliation is already done
            activity.runOnUiThread(() -> Toast.makeText(activity, "list of transaction is empty", Toast.LENGTH_SHORT).show());
        }
    }

    @Override
    public void onWrongApiCalled() {

    }

    @Override
    public void onRepeat(int i) {

    }

    private void printReport(M4BankMposClientInterfaceFacade clientInterface, PrintingType reportType, ExternalReconciliationData data) {
        clientInterface.cancel();
        if(reportType == PrintingType.RECONCILIATION_FULL_REPORT) {
            clientInterface.getPrinterManager().printReconciliationReportFull(new PrintingCallbackHandlerImpl(activity), data);
        } else {
            clientInterface.getPrinterManager().printReconciliationReportShort(new PrintingCallbackHandlerImpl(activity), data);
        }
    }
}
