import { PhotoHelper } from '@pura/picker_utils';
import { photoAccessHelper } from '@kit.MediaLibraryKit';
import { AppUtil, FileUtil, RandomUtil } from '@pura/harmony-utils';
import { fileIo, fileUri, picker } from '@kit.CoreFileKit';
import { EventConstants } from '../common/EventConstants';
import { MediaAction, MediaType } from '../manager/MediaManager';
import { LocalMediaManager } from '../manager/LocalMediaManager';
import { systemDateTime } from '@kit.BasicServicesKit';
import { image } from '@kit.ImageKit';

export class SaveUtils {

  /**
   * 保存pixelMap到相册
   * @param pixelMap
   * @returns
   */
  static async savePixelMapToAlbum(pixelMap: image.PixelMap): Promise<boolean> {
    try {
      const packOptions: image.PackingOption = {
        format: 'image/jpeg',
        quality: 80
      }
      let buffer = await image.createImagePacker().packToData(pixelMap, packOptions)
      // 应用沙箱路径
      let cachePath = FileUtil.getCacheDirPath() + FileUtil.separator + `scmf_${systemDateTime.getTime()}.jpeg`
      // 在沙箱新建并打开文件
      let file = fileIo.openSync(cachePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
      // 写入pixelMap图片内容
      fileIo.writeSync(file.fd, buffer)
      // 关闭文件
      fileIo.closeSync(file.fd)
      // 使用showAssetsCreationDialog保存沙箱中的图片
      let saved = await SaveUtils.saveImageVideoToAlbumDialog([cachePath])
      return Promise.resolve(saved)
    } catch (e) {
      console.error(e)
      return Promise.resolve(false)
    }
  }

  /**
   * 保存视频和图片到相册, 弹窗授权
   * @param path
   * @param name
   * @returns
   */
  static async saveImageVideoToAlbumDialog(srcFileUris: Array<string>, record: boolean = true): Promise<boolean> {
    try {
      // 基于弹窗授权的方式获取媒体库的目标uri
      let desFileUris: Array<string> = await PhotoHelper.showAssetsCreationDialog(srcFileUris);
      // 将来源于应用沙箱的照片内容写入媒体库的目标uri
      for (let i = 0; i < srcFileUris.length; i++) {
        let desFile: fileIo.File = await fileIo.open(desFileUris[i], fileIo.OpenMode.WRITE_ONLY);
        let srcFile: fileIo.File = await fileIo.open(srcFileUris[i], fileIo.OpenMode.READ_ONLY);
        await fileIo.copyFile(srcFile.fd, desFile.fd);
        fileIo.closeSync(srcFile);
        fileIo.closeSync(desFile);

        if (record) {
          LocalMediaManager.add(desFileUris[i])
          AppUtil.getContext().eventHub.emit(EventConstants.MediaActionEvent, srcFileUris[i].endsWith('mp4') ? MediaType.VIDEO : MediaType.IMAGE, MediaAction.ADD)
          console.debug('保存成功')
        }
      }
      return Promise.resolve(true)
    } catch (e) {
      console.error(e)
      return Promise.resolve(false)
    }
  }

  /**
   * 保存音频到本地, 无需ACL权限
   * @param path
   * @param name
   * @returns
   */
  static async saveAudioToMusic(srcFileUris: Array<string>): Promise<boolean> {
    try {
      const documentViewPicker = new picker.DocumentViewPicker(AppUtil.getContext())
      const documentSaveOptions = new picker.DocumentSaveOptions()
      documentSaveOptions.pickerMode = picker.DocumentPickerMode.DOWNLOAD
      const uriArray = await documentViewPicker.save(documentSaveOptions)
      let dirUri = uriArray[0]
      srcFileUris.forEach(async (srcUri) => {
        const srcPath = FileUtil.getFilePath(srcUri)
        const desUri = new fileUri.FileUri(dirUri + FileUtil.separator + FileUtil.getFileName(srcPath)).path
        const desFile = FileUtil.openSync(desUri, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE)
        await FileUtil.copyFile(srcPath, desFile.fd)
        LocalMediaManager.add(desUri)
        AppUtil.getContext().eventHub.emit(EventConstants.MediaActionEvent, MediaType.AUDIO, MediaAction.ADD)
        FileUtil.closeSync(desFile.fd)
        console.debug('保存成功')
      })
      return Promise.resolve(true)
    } catch (e) {
      console.error(e)
      return Promise.resolve(false)
    }
  }

  /**
   * 保存视频到相册, 需要ACL权限
   * @param path
   * @param name
   * @returns
   */
  static async saveVideoToAlbum(path: string, name: string): Promise<boolean> {
    try {
      let name = `scmf_${systemDateTime.getTime() + RandomUtil.getRandomInt(1000, 2000)}.mp4`
      const uri = await PhotoHelper.save(photoAccessHelper.PhotoType.VIDEO, 'mp4', { title: name.replace('.mp4', '') });
      let file = FileUtil.openSync(uri, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE);
      await FileUtil.copyFile(path, file.fd)
      LocalMediaManager.add(name)
      AppUtil.getContext().eventHub.emit(EventConstants.MediaActionEvent, MediaType.VIDEO, MediaAction.ADD)
      FileUtil.close(file)
      console.debug('保存成功')
      return Promise.resolve(true)
    } catch (e) {
      console.error(e)
      return Promise.resolve(false)
    }
  }

  /**
   * 保存图片到相册, 需要ACL权限
   * @param path
   * @param name
   * @returns
   */
  static async saveImageToAlbum(path: string, name: string): Promise<boolean> {
    try {
      if (FileUtil.accessSync(path)) name = `scmf_${systemDateTime.getTime() + RandomUtil.getRandomInt(1000, 2000)}.jpeg`
      const uri = await PhotoHelper.save(photoAccessHelper.PhotoType.IMAGE, 'jpeg', { title: name.replace('.jpeg', '') });
      let file = FileUtil.openSync(uri, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE);
      await FileUtil.copyFile(path, file.fd)
      LocalMediaManager.add(name)
      AppUtil.getContext().eventHub.emit(EventConstants.MediaActionEvent, MediaType.IMAGE, MediaAction.ADD)
      FileUtil.close(file)
      console.debug('保存成功')
      return Promise.resolve(true)
    } catch (e) {
      console.error(e)
      return Promise.resolve(false)
    }
  }
}