package kz.com.aman.kassa.plugins;

import android.content.ComponentName;
import android.content.Intent;
import android.os.Build;


import com.google.gson.Gson;

import java.util.List;

import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;
import kz.com.aman.kassa.MainActivity;

import kz.com.aman.kassa.model.AmanDao;

enum OperationType {
    PAYMENT, // payment
    REFUND, // return
    REVERSAL, // cancel
    CLOSE_DAY, // closing of the trading day
     OPERATIONS_LIST // get the list of operations
}

public class BankNfcPlugins implements MethodCallHandler {

    private final Gson gson = new Gson();

    //main activity
    private MainActivity activity;


    public MainActivity getActivity() {
        return this.activity;
    }

    public BankNfcPlugins(MainActivity activity) {
        this.activity = activity;
    }


    @Override
    public void onMethodCall(MethodCall call, Result result) {
        switch (call.method) {
            case "init":
                init(call, result);
                break;
            case "permissions":
                permissions(result);
                break;
            case "connection":
                connection(result);
                break;
            case "currency":
                currency(result);
                break;
            case "auth":
                authentication(call, result);
                break;
            case "pay":
                pay(call, result);
                break;
            case "cancel":
                cancel(call, result);
                break;
            case "shutdown":
                shutdown(call, result);
                break;
            case "closeDay":
                closeDay(call, result);
                break;
            case "transaction":
                showTransaction(call, result);
                break;
            case "findTransaction":
                findTransaction(call, result);
                break;
            case "refund":
                refund(call, result);
                break;
            case "version":
                result.success(String.valueOf(Build.VERSION.SDK_INT));
                break;
            case "get":
                AmanDao<String> dao = new AmanDao<>();
                dao.setSuccess(true);
                dao.setMsg("Hello World");
                result.success(gson.toJson(dao));
                break;
            case "error":
                result.error("0-code","0-message", "0-details");
                break;
            default:
                result.notImplemented();
        }
    }


    private static int getVersion() {
        String version = System.getProperty("java.version");
        if(version.startsWith("1.")) {
            version = version.substring(2, 3);
        } else {
            int dot = version.indexOf(".");
            if(dot != -1) { version = version.substring(0, dot); }
        } return Integer.parseInt(version);
    }

    private void permissions(Result result) {
//        try {
//            PermissionsManager.PermissionsCheckResultHandler permissionsCheckResultHandler =
//                    new PermissionsManager.PermissionsCheckResultHandler() {
//                        @Override
//                        public void onPermissionsGranted() {
//                            activity.runOnUiThread(() -> {
//                                        AmanDao<String> dao = new AmanDao<>();
//                                        dao.setSuccess(true);
//                                        dao.setMsg("OK");
//                                        result.success(gson.toJson(dao));
//                                    }
//                            );
//
//                        }
//
//                        @Override
//                        public void onPermissionsDeclined() {
//                            AmanDao<String> dao = new AmanDao<>();
//                            dao.setSuccess(false);
//                            dao.setMsg("decline");
//                            result.success(gson.toJson(dao));
//                        }
//                    };
//            permissionsManager = new PermissionsManagerImpl(this.activity);
//            permissionsManager.checkPermissions(permissionsCheckResultHandler);
//
//
//        } catch (Exception e) {
//            result.error("1", e.getMessage(), e.getLocalizedMessage());
//        }
    }


    private void init(MethodCall call, Result result) {
        String serverUrl = call.argument("serverUrl");
        String token = call.argument("token");
        start(token);
        AmanDao<String> dao = new AmanDao<>();
        dao.setSuccess(true);
        dao.setMsg("OK");
        result.success(gson.toJson(dao));

    }

    //start after all permissions granted
    private void start(String token) {
//        clientInterface = M4BankMposClient.getInstance(
//                new M4BankMposParameters(
//                        Format.JSON,
//                        "rus",
//                        null,
//                        this.activity,
//                        new SessionExpiringCallbackHandlerImpl(),
//                        "appName",
//                        ServerChoose.API_5_0,
//                        new ConfigurationSettings
//                                .Builder()
//                                .printerUsed(true)
//                                .umkaEnabled(true)
//                                .networkConfiguration(createNetworkConfiguration(serverUrl))
//                                .terminalConfiguration(createTerminalConfiguration())
//                                .build())
//        );
    }

    private void connection(Result result) {
//        clientInterface.getConfigurationManager()
//                .checkConnection(
//                        new ConnectionCheckHandlerImpl(this.activity, result));
    }
    private void currency(Result result) {
//        CurrencyDataHolder dataHolder = clientInterface.getConfigurationManager()
//                .getCurrencyDataHolder();
//        Currency currentCurrency = dataHolder.getCurrency();
//        if(currentCurrency!=null){
//            System.out.println(currentCurrency.getName());
//            System.out.println(currentCurrency.getCurrency3DigitCode());
//        } else {
//            System.out.println("currentCurrency is null");
//        }
//        System.out.println("===========================");
//        if(currentCurrency == null || !"398".equalsIgnoreCase(currentCurrency.getCurrency3DigitCode()) ){
//            List<Currency> currencies = dataHolder.getCurrencyList();
//            boolean changed = false;
//            for(Currency currency : currencies ){
//                System.out.println(currency.getName());
//                System.out.println(currency.getLetterCode());
//                System.out.println(currency.getCurrency3DigitCode());
//                if("398".equalsIgnoreCase(currency.getCurrency3DigitCode())){
//                    dataHolder.setCurrency(currency);
//                    changed = true;
//                    break;
//                }
//            }
//            AmanDao<String> dao = new AmanDao<>();
//            dao.setSuccess(changed);
//            dao.setMsg("current currency " + (currentCurrency!=null ? currentCurrency.getLetterCode() : "NULL"));
//            result.success(gson.toJson(dao));
//        } else {
//            AmanDao<String> dao = new AmanDao<>();
//            dao.setSuccess(true);
//            dao.setMsg("exist");
//            result.success(gson.toJson(dao));
//        }
    }



    private void authentication(MethodCall call, Result result) {
//        String login = call.argument("login");
//        String password = call.argument("password");
//        clientInterface.getAuthorizationManager().authorize(new AuthorizationHandlerImpl(this, result,  login, password) );
    }

    private void pay(MethodCall call, Result result) {
//        try {
//            Integer value = call.argument("amount");
//            long amount = value.longValue();
//            clientInterface.cancel();
//            clientInterface.getTransactionManager().makeCardPayment(new CardPaymentHandlerImpl(this, result, amount, TransactionTypeConv.PAYMENT));
//        } catch (Exception e) {
//            System.out.println("=============>ERROR:"+e.getMessage());
//            result.error("2", e.getMessage(), e.getLocalizedMessage());
//        }
    }

    private void findTransaction(MethodCall call, Result result) {
//        try {
//            Integer transactionNumber = call.argument("transactionNumber");
//            String authorizationCode = call.argument("authorizationCode");
//            clientInterface.getTransactionManager()
//                    .getTransactionsList(new CardRefundAmanHandlerImpl(this, result, transactionNumber, authorizationCode , transaction), 1000,
//                            0, GetOperationType.SHOW, null);
//        } catch (Exception e) {
//            System.out.println("=============>ERROR:"+e.getMessage());
//            result.error("2", e.getMessage(), e.getLocalizedMessage());
//        }
    }

    private void refund(MethodCall call, Result result) {
//        try {
//            clientInterface.getTransactionManager()
//                    .makeCardRefund(new CardRefundAmanHandlerImpl(this, result, null, null, transaction));
//        } catch (Exception e) {
//            System.out.println("=============>ERROR:"+e.getMessage());
//            result.error("2", e.getMessage(), e.getLocalizedMessage());
//        }
    }

    private void closeDay(MethodCall call, Result result) {
//        try {
//            clientInterface.cancel();
//            clientInterface.getTransactionManager().closeDay(new CloseDayHandlerImpl(this, result));
//        } catch (Exception e) {
//            System.out.println("=============>ERROR:"+e.getMessage());
//            result.error("2", e.getMessage(), e.getLocalizedMessage());
//        }
    }

    private void showTransaction(MethodCall call, Result result){
//        clientInterface.getTransactionManager()
//                .getTransactionsList(
//                        new TransactionDetailsHandlerImpl(this),
//                        20, 0,
//                        GetOperationType.SHOW,
//                        null);
    }

    private void cancel(MethodCall call, Result result) {
//        try {
//            clientInterface.cancel();
//            AmanDao<String> dao = new AmanDao<>();
//            dao.setSuccess(true);
//            dao.setMsg("OK");
//            result.success(gson.toJson(dao));
//        } catch (Exception e) {
//            System.out.println("=============>ERROR:"+e.getMessage());
//            result.error("2", e.getMessage(), e.getLocalizedMessage());
//        }
    }

    private void shutdown(MethodCall call, Result result) {
//        try {
//            clientInterface.shutdown();
//            AmanDao<String> dao = new AmanDao<>();
//            dao.setSuccess(true);
//            dao.setMsg("OK");
//            result.success(gson.toJson(dao));
//        } catch (Exception e) {
//            System.out.println("=============>ERROR:"+e.getMessage());
//            result.error("2", e.getMessage(), e.getLocalizedMessage());
//        }
    }


}