import { log } from './log';
import ffmpeg from 'fluent-ffmpeg';
import fs from 'fs';

const defaultVideoThumbB64 = '[encoded data, 5192 characters]';

export const defaultVideoThumb = Buffer.from(defaultVideoThumbB64, 'base64');

export async function getVideoInfo(filePath: string) {
  const size = fs.statSync(filePath).size;
  return new Promise<{
        width: number,
        height: number,
        time: number,
        format: string,
        size: number,
        filePath: string
    }>((resolve, reject) => {
      const ffmpegPath = process.env.FFMPEG_PATH;
      ffmpegPath && ffmpeg.setFfmpegPath(ffmpegPath);
      ffmpeg(filePath).ffprobe((err: any, metadata: any) => {
        if (err) {
          reject(err);
        } else {
          const videoStream = metadata.streams.find((s: { codec_type: string; }) => s.codec_type === 'video');
          if (videoStream) {
            log(`视频尺寸: ${videoStream.width}x${videoStream.height}`);
          } else {
            return reject('未找到视频流信息。');
          }
          resolve({
            width: videoStream.width, height: videoStream.height,
            time: parseInt(videoStream.duration),
            format: metadata.format.format_name,
            size,
            filePath
          });
        }
      });
    });
}

export async function encodeMp4(filePath: string) {
  const videoInfo = await getVideoInfo(filePath);
  log('视频信息', videoInfo);
  if (videoInfo.format.indexOf('mp4') === -1) {
    log('视频需要转换为MP4格式', filePath);
    // 转成mp4
    const newPath: string = await new Promise<string>((resolve, reject) => {
      const newPath = filePath + '.mp4';
      ffmpeg(filePath)
        .toFormat('mp4')
        .on('error', (err) => {
          reject(`转换视频格式失败: ${err.message}`);
        })
        .on('end', () => {
          log('视频转换为MP4格式完成');
          resolve(newPath); // 返回转换后的文件路径
        })
        .save(newPath);
    });
    return await getVideoInfo(newPath);
  }
  return videoInfo;
}

export function checkFfmpeg(newPath: string | null = null): Promise<boolean> {
  return new Promise((resolve, reject) => {
    log('开始检查ffmpeg', newPath);
    if (newPath) {
      ffmpeg.setFfmpegPath(newPath);
    }
    try {
      ffmpeg.getAvailableFormats((err: any, formats: any) => {
        if (err) {
          log('ffmpeg is not installed or not found in PATH:', err);
          resolve(false);
        } else {
          log('ffmpeg is installed.');
          resolve(true);
        }
      });
    } catch (e) {
      resolve(false);
    }
  });
}
