import image from '@ohos.multimedia.image';
const TAG = "sony_camera info"
export class PreviewManager {
  // 上下文对象
  private context: Context;
  // 当前活跃的显示缓冲区
  private activeBuffer: PixelMap | null = null;
  // 下一个准备显示的缓冲区
  private nextBuffer: PixelMap | null = null;
  // 处理状态标志，防止重复处理
  private isProcessing: boolean = false;
  // 缓冲区交换锁，防止并发交换
  private bufferLock: boolean = false;

  constructor(context: Context) {
    this.context = context;
  }
  //处理指定索引的帧
  async processFrame(index: number): Promise<boolean> {
    if (this.isProcessing)
    {
      console.info(TAG,"isprocessing")
      return false;
    }

    this.isProcessing = true;
    try {
      const filePath = `${this.context.filesDir}/live${index}.jpg`;

      // // 1. 文件检查
      // try {
      //   await fs.access(filePath); // 仅检查文件是否存在
      // } catch (error) {
      //   console.warn("文件访问失败:", error);
      //   return false;
      // }
      // 2. 创建图像源
      const imageSource = image.createImageSource(filePath);
      if (!imageSource) {
        console.warn(TAG,"创建ImageSource失败");
        return false;
      }
      try {
        // 3. 创建PixelMap
        const pixelMap = await imageSource.createPixelMap({
          // 添加降级选项
          desiredSize: { width: 720, height: 1280 }, // 限制分辨率
          desiredPixelFormat: 3 // RGB_565节省内存
        });
        if (!pixelMap) {
          console.warn(TAG,"创建PixelMap失败");
          return false;
        }
        // 5. 安全交换缓冲区
        this.nextBuffer = pixelMap;
        this.swapBuffers();
        return true;
      } finally {
        imageSource.release();
      }
    } catch (error) {
      console.error(TAG,`处理预览帧失败`, error);
      return false;
    } finally {
      this.isProcessing = false;
    }
  }
  //交换活跃缓冲区和下一个缓冲区
  private swapBuffers(): void {
    if (this.bufferLock) return;
    this.bufferLock = true;
    try {
      const oldBuffer = this.activeBuffer;
      this.activeBuffer = this.nextBuffer;
      this.nextBuffer = null;
      if (oldBuffer) {
        oldBuffer.release();
      }
    } finally {
      this.bufferLock = false;
    }
  }
  //获取当前活跃缓冲区
  async getActiveBuffer(): Promise<PixelMap | null> {
    return this.activeBuffer;
  }
  //检查是否准备好显示
  isReady(): boolean {
    return !this.isProcessing && this.activeBuffer !== null;
  }
  //检查是否有新帧等待处理
  hasNewFrame(): boolean {
    return this.nextBuffer !== null;
  }

  // getErrorCount():number{
  //   return this.errorCount
  // }
  // resetErrorCount(){
  //   this.errorCount = 0
  // }
  //释放资源
  release(): void {
    if (this.activeBuffer) {
      this.activeBuffer.release();
      this.activeBuffer = null;
    }
    if (this.nextBuffer) {
      this.nextBuffer.release();
      this.nextBuffer = null;
    }
  }
}