import { FileUtil } from "@pura/harmony-utils";
import fs from '@ohos.file.fs';
import { common } from "@kit.AbilityKit";
import { uniformTypeDescriptor } from '@kit.ArkData';
import { FileMd5Utils } from "./FileMd5Utils";

export class FileUtils {
  public static ROOT_DIR: string
  public static ID_CARD_DIR: string
  public static FILE_DIR: string
  public static IMAGE_DIR: string
  public static LOG_DIR: string

  constructor() {
  }

  /**
   * 初始化应用路径
   * @param uiContext
   */
  public static init(context: Context) {
    if (context) {
      FileUtils.ROOT_DIR = context.filesDir;
      FileUtils.ID_CARD_DIR = context.filesDir + "/IdCardPhoto";
      FileUtils.FILE_DIR = context.filesDir + "/File";
      FileUtils.IMAGE_DIR = context.filesDir + "/Image";
      FileUtils.LOG_DIR = context.filesDir + "/Log";
    }
  }

  public static createFileDir() {
    if (!FileUtil.accessSync(FileUtils.ID_CARD_DIR)) {
      FileUtil.mkdirSync(FileUtils.ID_CARD_DIR)
    }
    if (!FileUtil.accessSync(FileUtils.FILE_DIR)) {
      FileUtil.mkdirSync(FileUtils.FILE_DIR)
    }
    if (!FileUtil.accessSync(FileUtils.IMAGE_DIR)) {
      FileUtil.mkdirSync(FileUtils.IMAGE_DIR)
    }
    if (!FileUtil.accessSync(FileUtils.LOG_DIR)) {
      FileUtil.mkdirSync(FileUtils.LOG_DIR)
    }
  }


  public static async copyToLocal(src: string, dest: string): Promise<boolean> {
    // 创建目标路径（示例使用应用缓存目录）
    try {
      // 打开输入输出流
      let srcFile = await fs.open(src, fs.OpenMode.READ_ONLY);
      let destFile = await fs.open(dest, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);

      // 执行复制操作
      await fs.copyFile(srcFile.fd, destFile.fd);

      fs.closeSync(srcFile.fd)
      fs.closeSync(destFile.fd)
      return true
      // 关闭文件描述符
    } catch (err) {
      console.error(`文件复制失败: ${err.code}, ${err.message}`);
      return false
    }
  }

  private static MATCH_ARRAY: string[][] = [
    ["docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"],
    [".", "application/msword"],
    ["xls", "application/vnd.ms-excel"],
    ["xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"],
    ["ppt", "application/vnd.ms-powerpoint"],
    ["pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"],
    ["zip", "application/zip"],
    ["txt", "text/plain"],
    ["jpg", "image/jpeg"],
    ["jpeg", "image/jpeg"],
    ["png", "image/png"],
    ["gif", "image/gif"],
    ["mp3", "audio/mpeg"],
    ["mp4", "video/mp4"],
    ["m4u", "video/vnd.mpegurl"],
    ["m4v", "video/x-m4v"],
    ["avi", "video/x-msvideo"],
    ["pdf", "application/pdf"],
  ]

  static async openWithThirdPartyApp(context: common.UIAbilityContext, filePath: string) {
    // let fileExt = FileUtil.getFileExtention(filePath)
    // let fileUri = FileUtil.getFileUri(filePath).toString();

    FileMd5Utils.openFile(context, FileUtil.getFileName(filePath), filePath)
    return

  }
}