import { MediaRecordEntity } from '../entity/MediaRecordEntity';
import { LocalMediaManager } from './LocalMediaManager';
import { FileUtil, NumberUtil } from '@pura/harmony-utils';
import { fileIo as fs } from '@kit.CoreFileKit';
import { media } from '@kit.MediaKit';

export enum MediaAction {
  ADD, DELETE, CLEAR
}

export enum MediaType {
  VIDEO, IMAGE, AUDIO
}

export class MediaManager {

  /**
   * 获取相册中保存的视频
   * @returns
   */
  static async getVideoList(): Promise<Array<MediaRecordEntity>> {
    try {
      let mediaList = new Array<MediaRecordEntity>()

      let videoUris = LocalMediaManager.getAllVideos()
      for (let i = 0; i < videoUris.length; i++) {
        try {
          let uri = videoUris[i]
          let record = new MediaRecordEntity(uri)
          record.name = FileUtil.getFileName(uri)
          let file = FileUtil.openSync(uri)

          let videoSize: media.PixelMapParams = {}
          let avMetaDataExtractor: media.AVMetadataExtractor = await media.createAVMetadataExtractor();
          avMetaDataExtractor.fdSrc = file;
          let metadata = await avMetaDataExtractor.fetchMetadata();
          videoSize.width = parseInt(metadata.videoWidth as string);
          videoSize.height = parseInt(metadata.videoHeight as string);

          let avImageGenerator = await media.createAVImageGenerator();
          if (avImageGenerator) {
            avImageGenerator.fdSrc = file;
            record.thumb =
              await avImageGenerator.fetchFrameByTime(0, media.AVImageQueryOptions.AV_IMAGE_QUERY_CLOSEST_SYNC,
                videoSize);
          } else {
            console.error('Create AVImageGenerator failed!');
          }
          mediaList.push(record)
        } catch (e) {
          console.error(e)
        }
      }
      return Promise.resolve(mediaList)
    } catch (err) {
      console.error('video failed with err: ' + err);
      return Promise.reject(err)
    }
  }

  /**
   * 获取相册中保存的图片
   * @returns
   */
  static async getImageList(): Promise<Array<MediaRecordEntity>> {
    let mediaList = new Array<MediaRecordEntity>()

    let imageUri = LocalMediaManager.getAllImages()
    for (let i = 0; i < imageUri.length; i++) {
      try {
        let uri = imageUri[i]
        let file = FileUtil.openSync(uri)
        let record = new MediaRecordEntity(uri)
        record.name = FileUtil.getFileName(uri)
        mediaList.push(record)
      } catch (e) {
        console.error(e)
      }
    }
    return Promise.resolve(mediaList)
  }

  /**
   * 获取保存的音频
   * @returns
   */
  static async getAudioList(): Promise<Array<MediaRecordEntity>> {
    try {
      let mediaList = new Array<MediaRecordEntity>()

      let audioUris = LocalMediaManager.getAllAudios()
      for (let i = 0; i < audioUris.length; i++) {
        let uri = audioUris[i]
        let filePath = FileUtil.getFilePath(uri)
        if (FileUtil.accessSync(filePath)) {
          let record = new MediaRecordEntity(filePath)
          record.name = FileUtil.getFileName(filePath)
          let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE)
          let stat = fs.statSync(file.fd)
          record.createTime = stat.ctime
          let avMetadataExtractor = await media.createAVMetadataExtractor()
          avMetadataExtractor.fdSrc = file
          // 获取元数据（promise模式）
          let result = await avMetadataExtractor.fetchMetadata()
          record.duration = result.duration ? NumberUtil.toNumber(result.duration) : 0
          avMetadataExtractor.release()
          fs.close(file)
          mediaList.push(record)
        } else {
          LocalMediaManager.delete(uri)
        }
      }
      return Promise.resolve(mediaList)
    } catch (err) {
      console.error('audio failed with err: ' + err);
      return Promise.reject(err)
    }
  }
}