import usbManager from '@ohos.usbManager';
import { BusinessError } from '@ohos.base';

// 定义常用USB设备ID常量数组
export const USBDeviceIds: Array<UsbDeviceInfo> = [
  {
    DeviceName: "Sony_Camera",
    VendorId: 0x054c,
    ProductId: 0x0caa
  },
  {
    DeviceName: "Scanning_Gun",
    VendorId: 0x23d0,
    ProductId: 0x0c80
  }
];

// USB设备信息接口
interface UsbDeviceInfo {
  DeviceName: string
  VendorId: number
  ProductId: number
}

// USB设备管理类（单例）
export class USBDeviceManager {
  // 单例实例
  private static instance: USBDeviceManager | null = null;
  // 存储已连接的USB设备列表
  private connectedDevices: Array<usbManager.USBDevice> = [];
  // 定时器ID
  private checkIntervalId: number | null = null;

  // 私有构造函数
  private constructor() {
    this.refreshDeviceList();
    this.startAutoCheck();
  }

  // 获取单例实例
  public static getInstance(): USBDeviceManager {
    if (!USBDeviceManager.instance) {
      USBDeviceManager.instance = new USBDeviceManager();
    }
    return USBDeviceManager.instance;
  }

  // 开始自动检测（每2秒一次）
  private startAutoCheck(): void {
    // 先停止已有的定时器
    this.stopAutoCheck();

    // 启动新的定时器
    this.checkIntervalId = setInterval(() => {
      this.refreshDeviceList();
      this.checkDevices();
    }, 2000);
  }

  // 停止自动检测
  public stopAutoCheck(): void {
    if (this.checkIntervalId !== null) {
      clearInterval(this.checkIntervalId);
      this.checkIntervalId = null;
    }
  }

  // 检查设备连接状态
  private checkDevices(): void {
    if (this.hasConnectedDevices()) {
      const isCameraConnected = this.isDeviceConnectedByName('Sony_Camera');
      const isScannerConnected = this.isDeviceConnectedByName('Scanning_Gun');
      AppStorage.setOrCreate<boolean>('CameraStatus', isCameraConnected);
      AppStorage.setOrCreate<boolean>('ScanningGunStatus', isScannerConnected);
    } else {
      console.log('USB状态检测', '没有USB设备连接');
    }
  }

  // 刷新设备列表，获取当前系统已连接的所有USB设备
  public refreshDeviceList(): void {
    try {
      this.connectedDevices = usbManager.getDevices();
      console.log('[USBDeviceManager] 当前连接的设备:', this.connectedDevices);
    } catch (error) {
      console.error('[USBDeviceManager] 获取USB设备失败:', (error as BusinessError).message);
      this.connectedDevices = [];
    }
  }

  // 检查是否有USB设备连接
  public hasConnectedDevices(): boolean {
    return this.connectedDevices.length > 0;
  }

  // 根据供应商ID和产品ID检查特定USB设备是否连接
  public isDeviceConnectedById(vendorId: number, productId: number): boolean {
    return this.connectedDevices.some(device =>
    device.vendorId === vendorId && device.productId === productId
    );
  }

  // 根据设备信息检查USB设备是否连接
  public isDeviceConnectedByInfo(usbDevice: UsbDeviceInfo): boolean {
    return this.isDeviceConnectedById(usbDevice.VendorId, usbDevice.ProductId);
  }

  // 根据预定义的设备名称检查USB设备是否连接
  public isDeviceConnectedByName(deviceName: string): boolean {
    const deviceInfo = USBDeviceIds.find(item => item.DeviceName === deviceName);

    if (!deviceInfo) {
      console.warn(`[USBDeviceManager] 设备 ${deviceName} 不在预定义列表中`);
      return false;
    }
    return this.isDeviceConnectedById(deviceInfo.VendorId, deviceInfo.ProductId);
  }

  // 获取所有已连接的USB设备
  public getAllDevices(): Array<usbManager.USBDevice> {
    return [...this.connectedDevices]; // 返回副本以避免外部修改
  }

  // 销毁实例
  public destroy(): void {
    this.stopAutoCheck();
    USBDeviceManager.instance = null; // 现在可以正常赋值为null
  }
}