import { buffer } from '@kit.ArkTS';
import { fileIo } from '@kit.CoreFileKit';
import { fileUri } from "@kit.CoreFileKit";
import { hilog } from '@kit.PerformanceAnalysisKit';
import { image } from '@kit.ImageKit';

export class BitMapUtils{

  /**
   * 保存图片到本地
   * @param data        图片base64
   * @param filesDir    保存目录
   * @param fileName    保存的文件名
   * @returns
   */
   static async writeFile(data: string, filesDir :string,fileName:string): Promise<string> {
     let  fileAbsolutelyPath =""
    try {
      let filePath = filesDir+"/" + fileName;
      // uri = fileUri.getUriFromPath(filePath);
      fileAbsolutelyPath = filePath
      let file = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE);
      console.info("file fd: " + file.fd);
      const reg = new RegExp("data:image/\\w+;base64,")
      const base64 = data.replace(reg, "");
      console.log("base64flag", base64)
      const dataBuffer = buffer.from(base64, 'base64')
      let writeLen = fileIo.writeSync(file.fd, dataBuffer.buffer);
      hilog.info(0xA0c0d0,'文件长度',writeLen+"")
      fileIo.closeSync(file);
    } catch (Error) {
      hilog.error(0xA0c0d0,'Error',Error.code)
    }
    return fileAbsolutelyPath;
  }


 static  async  copyPixelMap(pm: image.PixelMap): Promise<image.PixelMap> {
   const imageInfo: image.ImageInfo = await pm.getImageInfo();
   const buffer: ArrayBuffer = new ArrayBuffer(pm.getPixelBytesNumber());
   // TODO 知识点：通过readPixelsToBuffer实现PixelMap的深拷贝，其中readPixelsToBuffer输出为BGRA_8888
   await pm.readPixelsToBuffer(buffer);
   // TODO 知识点：readPixelsToBuffer输出为BGRA_8888,此处createPixelMap需转为RGBA_8888
   const opts: image.InitializationOptions = {
     editable: true,
     pixelFormat: image.PixelMapFormat.RGBA_F16,
     size: { height: imageInfo.size.height, width: imageInfo.size.width }
   };
   return await image.createPixelMap(buffer, opts);
  }

}
// data为需要转换的base64字符串，返回沙箱路径uri