import React from 'react';
import { MPosLookup, InterfaceType } from "react-native-bixolon-bgatelib";
import { DeviceInfo } from "./DeviceInfo";
import { DiscoveryResponse } from "./Interfaces";
import { Platform } from 'react-native';

export async function DiscoveryDevice(
    interfaceString: String,
    setDeviceList: React.Dispatch<DeviceInfo[]>,
    setProcessing: React.Dispatch<boolean>) {

    const lookup = new MPosLookup();
    const deviceList = new Array<DeviceInfo>();

    setProcessing(true);

    switch (interfaceString) {
        case "Bluetooth":
            try {
                let json = JSON.parse(await lookup.getBluetoothDevices());
                await addDeviceList(json, deviceList)
            }
            catch (e) { console.error("Error : getBluetoothDevices"); }
        
            try {
                let json = JSON.parse(await lookup.getBLEDevices());
                await addDeviceList(json, deviceList)
            }
            catch (e) { console.error("Error : getBLEDevices"); }
        break;

        case "Network":
            try {
                let json = JSON.parse(await lookup.getNetworkDevices());
                await addDeviceList(json, deviceList)
            }
            catch (e) { console.error("Error : getNetworkDevices"); }
        break;

        case "USB":
            try {
                let json = JSON.parse(await lookup.getUSBDevices());
                await addDeviceList(json, deviceList)
            }
            catch (e) { console.error("Error : getUSBDevices"); }
        break;
    }

    setProcessing(false);
    setDeviceList(deviceList);
}

function addDeviceList(json: Array<DiscoveryResponse>, deviceList: Array<DeviceInfo>) {
    for (let i in json) {
        const address = json[i].address;
        const interfacetype = json[i].interfacetype;

        let deviceName = InterfaceType[interfacetype] + " " + i;
        try {
            deviceName = json[i].devicename.trim();
        } catch (e) {

        }

        if (Platform.OS == 'android' && interfacetype == 16) {
            const product = json[i].product;
            const device = new DeviceInfo(product, deviceName, interfacetype);
            deviceList.push(device);
        } else {
            const device = new DeviceInfo(deviceName, address, interfacetype);
            deviceList.push(device);
        }
    }
}
