import { media } from "@kit.MediaKit";
import { FileUtil } from "@pura/harmony-utils";
import { fileIo } from "@kit.CoreFileKit";

export class MediaUtils {

  static async getVideoSize(uri: string): Promise<media.PixelMapParams> {
    let videoSize: media.PixelMapParams = {};
    let avMetaDataExtractor: media.AVMetadataExtractor = await media.createAVMetadataExtractor();
    try {
      let file = FileUtil.openSync(uri);
      avMetaDataExtractor.fdSrc = file;
      let metadata = await avMetaDataExtractor.fetchMetadata()
      videoSize.width = parseInt(metadata.videoWidth as string);
      videoSize.height = parseInt(metadata.videoHeight as string);
      return Promise.resolve(videoSize)
    } catch (e) {
      let cacheFilePath = FileUtil.getCacheDirPath() + '/' + FileUtil.getFileName(uri)
      try {
        let file = FileUtil.openSync(uri, fileIo.OpenMode.READ_ONLY);
        // 复制文件到缓存目录下
        FileUtil.copyFileSync(file.fd, cacheFilePath)

        avMetaDataExtractor.fdSrc = FileUtil.openSync(cacheFilePath);
        let metadata = await avMetaDataExtractor.fetchMetadata()
        videoSize.width = parseInt(metadata.videoWidth as string);
        videoSize.height = parseInt(metadata.videoHeight as string);
        return Promise.resolve(videoSize)
      } catch (e) {
        return Promise.reject(e)
      } finally {
        if (FileUtil.accessSync(cacheFilePath)) {
          FileUtil.unlink(cacheFilePath)
        }
      }
    }
  }
}