import { abilityAccessCtrl, Permissions } from '@kit.AbilityKit'
import { photoAccessHelper } from '@kit.MediaLibraryKit'
import fs from '@ohos.file.fs'
import { promptAction } from '@kit.ArkUI'
import EZLog from './EZLog'

const TAG = 'EZMediaFileUtil'

export default class EZMediaFileUtil {
  static async saveMediaToAlbum(sourceMediaPath: string, photoType: photoAccessHelper.PhotoType) {
    let r2 = await EZMediaFileUtil.checkWRITE_IMAGEVIDEOPermission()
    if (!r2) {
      EZLog.error(TAG, 'not apply WRITE_IMAGEVIDEO Permission')
      return
    }
    EZLog.info(TAG, `saveMediaToAlbum start ${sourceMediaPath}`)
    const helper = photoAccessHelper.getPhotoAccessHelper(getContext())
    try {
      // 创建文件资产
      const fileFormat = photoType == photoAccessHelper.PhotoType.VIDEO ? 'mp4' : 'jpg'
      const mediaUri = await helper.createAsset(photoType, fileFormat)
      const mediaFile = await fs.open(mediaUri, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE)

      // 打开源视频文件
      const sourceFile = await fs.open(sourceMediaPath, fs.OpenMode.READ_ONLY)

      // 获取源视频文件大小
      const sourceFileStat = await fs.stat(sourceFile.fd)
      const buffer = new Uint8Array(sourceFileStat.size)

      // 读取源视频文件数据
      fs.readSync(sourceFile.fd, buffer.buffer)

      // 将数据写入新创建的相册视频文件
      fs.writeSync(mediaFile.fd, buffer.buffer)

      // 关闭文件
      await fs.close(mediaFile.fd)
      await fs.close(sourceFile.fd)

      promptAction.showToast({
        message: `已保存至相册`
      })
      EZLog.info(TAG, `saveMediaToAlbum succeed`)
    } catch (error) {
      EZLog.error(TAG, `saveMediaToAlbum error: ${JSON.stringify(error)}`)
    }
  }


  // 检查WRITE_IMAGEVIDEO权限(允许应用读写媒体库的图片和视频媒体文件信息。)
  static async checkWRITE_IMAGEVIDEOPermission(): Promise<boolean> {
    let ret = await EZMediaFileUtil.checkAndRequestPermission(getContext(), ['ohos.permission.WRITE_IMAGEVIDEO'])
    return ret.valueOf()
  }

  // 检查READ_IMAGEVIDEO权限(允许应用读取媒体库的图片和视频媒体文件信息。)
  private static async checkREAD_IMAGEVIDEOPermission(): Promise<boolean> {
    let ret = await EZMediaFileUtil.checkAndRequestPermission(getContext(), ['ohos.permission.READ_IMAGEVIDEO'])
    return ret.valueOf()
  }

  // 检查并获取权限
  private static async checkAndRequestPermission(context: Context, permissionList: Permissions[]): Promise<boolean> {
    let grantedAll = true
    let grantStatus: number[] = await EZMediaFileUtil.requestPermission(context, permissionList)

    for (let index = 0; index < grantStatus.length; index++) {
      EZLog.info(TAG, `checkAndRequestPermission: ${grantStatus[index]}`)
      if (grantStatus[index] != abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) {
        grantedAll = false
      }
    }
    return Promise.resolve(grantedAll)
  }

  // 直接获取权限
  private static async requestPermission(context: Context, permissionList: Permissions[]): Promise<number[]> {
    let requestResult = await abilityAccessCtrl.createAtManager().requestPermissionsFromUser(context, permissionList)
    return requestResult.authResults
  }
}