import { NativeEventEmitter, NativeModules, Platform, type EmitterSubscription } from 'react-native';
import { NPrinter } from './NPrinter';
import type { INPrinterScanControllerCallback } from './INPrinterScanControllerCallback';

const LINKING_ERROR =
    `The package 'react-native-nemonic-sdk' doesn't seem to be linked. Make sure: \n\n` +
    Platform.select({ ios: "- You have run 'pod install'\n", default: '' }) +
    '- You rebuilt the app after installing the package\n' +
    '- You are not using Expo Go\n';

const NPrinterScanControllerModule = NativeModules.NPrinterScanControllerModule
    ? NativeModules.NPrinterScanControllerModule
    : new Proxy(
        {},
        {
            get() {
                throw new Error(LINKING_ERROR);
            },
        }
    );

export class NPrinterScanController {

    private static callback: INPrinterScanControllerCallback;

    private eventEmitter: NativeEventEmitter;
    private eventDeviceFoundListener?: EmitterSubscription;

    constructor(callback: INPrinterScanControllerCallback) {
        NPrinterScanController.callback = callback;
        this.eventEmitter = new NativeEventEmitter(NPrinterScanControllerModule);
    }

    public startScan(): Promise<number> {
        this.registerEvent()
        return NPrinterScanControllerModule.startScan();
    }

    public stopScan() {
        NPrinterScanControllerModule.stopScan()
        this.unregisterEvent()
    }

    private deviceFound(params: any) {
        var name = params.name as string
        var macAddress = params.macAddress as string
        var type = params.type as number

        var printer = new NPrinter()
        printer.setName(name)
        printer.setMacAddress(macAddress)
        printer.setType(type)

        console.log(name + '(' + macAddress + ')')

        NPrinterScanController.callback.deviceFound(printer)
    }

    private registerEvent() {
        this.eventDeviceFoundListener = this.eventEmitter.addListener('deviceFound', this.deviceFound)
    }

    private unregisterEvent() {
        this.eventDeviceFoundListener?.remove()
    }
}
