// Shared printer device manager for WebUSB label printers (Print.vue) - centralizes device
// enumeration and preferred-printer memory, mirroring cameraManager.js's approach for webcams.
class PrinterManager {
    constructor() {
        this.availableDevices = [];
    }

    // A USB device has no stable "deviceId" like MediaDeviceInfo - vendorId+productId+serialNumber
    // is the closest stable identity across plug/unplug and page reloads (empty serial number still
    // uniquely identifies the common single-printer-of-that-model setup).
    printerId(device) {
        return `${device.vendorId}:${device.productId}:${device.serialNumber || ''}`;
    }

    async enumerateDevices() {
        try {
            this.availableDevices = await navigator.usb.getDevices();
            return this.availableDevices;
        } catch (err) {
            console.error('Error enumerating printers:', err);
            return [];
        }
    }

    getAvailableDevices() {
        return this.availableDevices;
    }

    getRecentPrinters() {
        try {
            const saved = localStorage.getItem('recentPrinterIds');
            return saved ? JSON.parse(saved) : [];
        } catch (err) {
            console.error('Error loading recent printers:', err);
            return [];
        }
    }

    savePreferredPrinter(device) {
        const printerId = this.printerId(device);
        const recentPrinters = this.getRecentPrinters();
        const updated = [printerId, ...recentPrinters.filter((id) => id !== printerId)];

        try {
            localStorage.setItem('recentPrinterIds', JSON.stringify(updated));
        } catch (err) {
            console.error('Error saving recent printers:', err);
        }
    }

    // Most-recently-used device that's among `devices` (already-paired printers currently
    // visible), for auto-connecting on page load / when a printer is plugged back in - same
    // "recent list, first still-present match wins" logic as cameraManager's loadPreferredCamera.
    findPreferredDevice(devices) {
        const recentPrinters = this.getRecentPrinters();
        for (const printerId of recentPrinters) {
            const device = devices.find((d) => this.printerId(d) === printerId);
            if (device) {
                return device;
            }
        }
        return null;
    }
}

export default new PrinterManager();
