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;
}

export
class USBDeviceManager {
  private connectedDevices: Array<usbManager.USBDevice> = [];
  private pollTimer: number | null = null;
  private isPollingPaused: boolean = false;

  // 启动轮询（带暂停控制）
  public startPolling(interval: number, callback: (devices: usbManager.USBDevice[]) => void): void {
    this.stopPolling(); // 先停止已有轮询
    this.pollTimer = setInterval(async () => {
      if (this.isPollingPaused) return; // 暂停时跳过检测
      try {
        this.connectedDevices = await this.refreshDeviceList();
        callback(this.connectedDevices);
      } catch (error) {
        console.error('轮询失败:', (error as BusinessError).message);
      }
    }, interval)  as number; // 鸿蒙中setInterval返回类型需转换
  }

  // 暂停轮询
  public pausePolling(): void {
    this.isPollingPaused = true;
  }

  // 恢复轮询
  public resumePolling(): void {
    this.isPollingPaused = false;
  }

  // 停止轮询（释放资源）
  public stopPolling(): void {
    if (this.pollTimer !== null) {
      clearInterval(this.pollTimer);
      this.pollTimer = null;
    }
    this.isPollingPaused = false;
  }

  /* 手动刷新设备列表（需主动调用）
  * @returns 返回刷新后的设备列表
  */
  public async refreshDeviceList(): Promise<Array<usbManager.USBDevice>> {
    try {
      this.connectedDevices = usbManager.getDevices();
      console.log('[USB] 当前连接的设备:', this.connectedDevices);
      return this.connectedDevices;
    } catch (error) {
      console.error('[USB] 获取USB设备失败:', (error as BusinessError).message);
      this.connectedDevices = [];
      return [];
    }
  }

  /* 检查是否有USB设备连接
  * @param forceRefresh 是否强制刷新设备列表
  */
  public async hasConnectedDevices(forceRefresh: boolean = false): Promise<boolean> {
    if (forceRefresh || this.connectedDevices.length === 0) {
      await this.refreshDeviceList();
    }
    return this.connectedDevices.length > 0;
  }

  /* 检查特定设备是否连接
  * @param vendorId 厂商ID
  * @param productId 产品ID
  * @param forceRefresh 是否强制刷新
  */
  public async isDeviceConnectedById(
    vendorId: number,
    productId: number,
    forceRefresh: boolean = false
  ): Promise<boolean> {
    if (forceRefresh) {
      await this.refreshDeviceList();
    }
    return this.connectedDevices.some(device =>
    device.vendorId === vendorId && device.productId === productId
    );
  }

  /* 检查预定义的设备是否连接
  * @param deviceName 设备名称（需在USBDeviceIds中定义）
  * @param forceRefresh 是否强制刷新
  */
  public async isDeviceConnectedByName(
    deviceName: string,
    forceRefresh: boolean = false
  ): Promise<boolean> {
    const deviceInfo = USBDeviceIds.find(item => item.DeviceName === deviceName);
    if (!deviceInfo) {
      console.warn(`[USB] 设备 ${deviceName} 不在预定义列表中`);
      return false;
    }
    return this.isDeviceConnectedById(deviceInfo.VendorId, deviceInfo.ProductId, forceRefresh);
  }

  /*
  * 获取当前缓存的设备列表（不主动刷新）
  */
  public getCachedDevices(): Array<usbManager.USBDevice> {
    return [...this.connectedDevices];
  }
}