package com.example.bdkipoc.transaction.managers;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.RemoteException;
import android.util.Log;

import com.example.bdkipoc.MyApplication;
import com.sunmi.pay.hardware.aidl.AidlConstants.CardType;
import com.sunmi.pay.hardware.aidlv2.AidlConstantsV2;
import com.sunmi.pay.hardware.aidlv2.readcard.CheckCardCallbackV2;

/**
 * CardScannerManager - Handles card detection for both EMV and Simple modes
 */
public class CardScannerManager {
    private static final String TAG = "CardScannerManager";
    
    private CardScannerCallback callback;
    private boolean isProcessing = false;
    
    public interface CardScannerCallback {
        void onCardDetected(String cardType, Bundle cardData);
        void onEMVCardDetected(int cardType);
        void onScanError(String errorMessage);
        void onScanProgress(String message);
    }
    
    public CardScannerManager(CardScannerCallback callback) {
        this.callback = callback;
    }
    
    public void startScanning(boolean isEMVMode) {
        if (isProcessing) {
            Log.d(TAG, "Card check already in progress - ignoring call");
            return;
        }
        
        Log.d(TAG, "Starting card check - setting isProcessing = true");
        isProcessing = true;
        
        try {
            // Small delay to ensure everything is ready
            new Handler(Looper.getMainLooper()).postDelayed(() -> {
                if (isProcessing) {
                    if (isEMVMode) {
                        startEMVCardCheck();
                    } else {
                        startSimpleCardCheck();
                    }
                }
            }, 500);
            
        } catch (Exception e) {
            Log.e(TAG, "Error in startScanning: " + e.getMessage(), e);
            handleScanError("Error: " + e.getMessage());
        }
    }
    
    public void stopScanning() {
        try {
            if (MyApplication.app != null && MyApplication.app.readCardOptV2 != null) {
                MyApplication.app.readCardOptV2.cancelCheckCard();
            }
            isProcessing = false;
            Log.d(TAG, "Card scanning stopped");
        } catch (Exception e) {
            Log.e(TAG, "Error stopping card check: " + e.getMessage());
        }
    }
    
    public boolean isScanning() {
        return isProcessing;
    }
    
    private void startEMVCardCheck() {
        try {
            if (callback != null) {
                callback.onScanProgress("EMV Mode: Starting card scan...");
            }
            
            int cardType = AidlConstantsV2.CardType.NFC.getValue() | AidlConstantsV2.CardType.IC.getValue();
            Log.d(TAG, "Starting EMV checkCard with cardType: " + cardType);
            
            MyApplication.app.readCardOptV2.checkCard(cardType, mEMVCheckCardCallback, 60);
            
        } catch (Exception e) {
            e.printStackTrace();
            Log.e(TAG, "Error in startEMVCardCheck: " + e.getMessage());
            handleScanError("Error starting EMV card scan: " + e.getMessage());
        }
    }
    
    private void startSimpleCardCheck() {
        try {
            if (!MyApplication.app.isConnectPaySDK()) {
                if (callback != null) {
                    callback.onScanProgress("Connecting to PaySDK...");
                }
                MyApplication.app.bindPaySDKService();
                return;
            }
            
            if (callback != null) {
                callback.onScanProgress("Simple Mode: Starting card scan...");
            }
            
            int cardType = CardType.MAGNETIC.getValue() | CardType.IC.getValue() | CardType.NFC.getValue();
            
            MyApplication.app.readCardOptV2.checkCard(cardType, mSimpleCheckCardCallback, 60);
            
        } catch (Exception e) {
            e.printStackTrace();
            handleScanError("Error starting card scan: " + e.getMessage());
        }
    }
    
    private void handleScanError(String errorMessage) {
        Log.e(TAG, "Scan error: " + errorMessage);
        isProcessing = false;
        
        if (callback != null) {
            callback.onScanError(errorMessage);
        }
    }
    
    public void resetScanning() {
        Log.d(TAG, "Resetting scanning state");
        isProcessing = false;
    }
    
    // Simple Card Detection Callback
    private final CheckCardCallbackV2 mSimpleCheckCardCallback = new CheckCardCallbackV2.Stub() {
        @Override
        public void findMagCard(Bundle info) throws RemoteException {
            Log.d(TAG, "Simple Mode: findMagCard callback triggered");
            isProcessing = false;
            if (callback != null) {
                callback.onCardDetected("MAGNETIC", info);
            }
        }

        @Override
        public void findICCard(String atr) throws RemoteException {
            Bundle info = new Bundle();
            info.putString("atr", atr);
            isProcessing = false;
            if (callback != null) {
                callback.onCardDetected("IC", info);
            }
        }

        @Override
        public void findRFCard(String uuid) throws RemoteException {
            Bundle info = new Bundle();
            info.putString("uuid", uuid);
            isProcessing = false;
            if (callback != null) {
                callback.onCardDetected("NFC", info);
            }
        }

        @Override
        public void onError(int code, String message) throws RemoteException {
            isProcessing = false;
            if (callback != null) {
                callback.onScanError("Card error: " + message);
            }
        }

        @Override
        public void findICCardEx(Bundle info) throws RemoteException {
            isProcessing = false;
            if (callback != null) {
                callback.onCardDetected("IC", info);
            }
        }

        @Override
        public void findRFCardEx(Bundle info) throws RemoteException {
            isProcessing = false;
            if (callback != null) {
                callback.onCardDetected("NFC", info);
            }
        }

        @Override
        public void onErrorEx(Bundle info) throws RemoteException {
            isProcessing = false;
            String msg = info.getString("message", "Unknown error");
            if (callback != null) {
                callback.onScanError("Card error: " + msg);
            }
        }
    };
    
    // EMV Card Detection Callback
    private final CheckCardCallbackV2 mEMVCheckCardCallback = new CheckCardCallbackV2.Stub() {
        @Override
        public void findMagCard(Bundle info) throws RemoteException {
            isProcessing = false;
            if (callback != null) {
                callback.onCardDetected("MAGNETIC", info);
            }
        }

        @Override
        public void findICCard(String atr) throws RemoteException {
            MyApplication.app.basicOptV2.buzzerOnDevice(1, 2750, 200, 0);
            isProcessing = false;
            if (callback != null) {
                callback.onEMVCardDetected(AidlConstantsV2.CardType.IC.getValue());
            }
        }

        @Override
        public void findRFCard(String uuid) throws RemoteException {
            isProcessing = false;
            if (callback != null) {
                callback.onEMVCardDetected(AidlConstantsV2.CardType.NFC.getValue());
            }
        }

        @Override
        public void onError(int code, String message) throws RemoteException {
            isProcessing = false;
            if (callback != null) {
                callback.onScanError("EMV Error: " + message);
            }
        }

        @Override
        public void findICCardEx(Bundle info) throws RemoteException {
            isProcessing = false;
            if (callback != null) {
                callback.onEMVCardDetected(AidlConstantsV2.CardType.IC.getValue());
            }
        }

        @Override
        public void findRFCardEx(Bundle info) throws RemoteException {
            isProcessing = false;
            if (callback != null) {
                callback.onEMVCardDetected(AidlConstantsV2.CardType.NFC.getValue());
            }
        }

        @Override
        public void onErrorEx(Bundle info) throws RemoteException {
            isProcessing = false;
            String msg = info.getString("message", "Unknown error");
            if (callback != null) {
                callback.onScanError("EMV Error: " + msg);
            }
        }
    };
}