package com.moka.gdtauto.util;

import org.bytedeco.javacv.FFmpegFrameRecorder;
import org.bytedeco.javacv.Java2DFrameConverter;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;

/**
 * 视频水印简单测试程序
 * 可以直接运行main方法进行测试
 * 注意：视频处理较慢，请耐心等待
 */
public class VideoWatermarkSimpleTest {

    public static void main(String[] args) {
        try {
            String outputDir = "target/test-output/video-watermark";
            File dir = new File(outputDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            // 创建测试视频（3秒，10fps）
            String inputPath = outputDir + "/test-input.mp4";
            if (!new File(inputPath).exists()) {
                System.out.println("正在创建测试视频（3秒，10fps）...");
                createTestVideo(inputPath, 1280, 720, 10, 3);
                System.out.println("✓ 创建测试视频成功: " + inputPath);
            } else {
                System.out.println("✓ 使用已存在的测试视频: " + inputPath);
            }

            // 测试1: 基本视频水印功能
            System.out.println("\n开始测试1: 基本视频水印功能...");
            String outputPath1 = outputDir + "/output-basic.mp4";
            VideoWatermarkUtil.addWatermark(inputPath, outputPath1, "《绝世龙王》");
            System.out.println("✓ 测试1通过: 基本视频水印功能 -> " + outputPath1);

            // 测试2: 提取第一帧
            System.out.println("\n开始测试2: 提取视频第一帧...");
            String firstFramePath = outputDir + "/first-frame.jpg";
            VideoWatermarkUtil.extractFirstFrame(inputPath, firstFramePath);
            System.out.println("✓ 测试2通过: 提取第一帧 -> " + firstFramePath);

            System.out.println("\n========================================");
            System.out.println("所有测试通过！✓");
            System.out.println("测试结果保存在: " + new File(outputDir).getAbsolutePath());
            System.out.println("========================================");

        } catch (Exception e) {
            System.err.println("✗ 测试失败: " + e.getMessage());
            e.printStackTrace();
            System.exit(1);
        }
    }

    /**
     * 创建测试视频
     */
    @SuppressWarnings("resource")
    private static void createTestVideo(String path, int width, int height, double frameRate, int duration) throws Exception {
        FFmpegFrameRecorder recorder = null;
        Java2DFrameConverter converter = new Java2DFrameConverter();

        try {
            recorder = new FFmpegFrameRecorder(path, width, height, 0);
            recorder.setVideoCodec(org.bytedeco.ffmpeg.global.avcodec.AV_CODEC_ID_H264);
            recorder.setFormat("mp4");
            recorder.setFrameRate(frameRate);
            recorder.setVideoBitrate(2000000);
            recorder.start();

            int totalFrames = (int) (frameRate * duration);

            for (int i = 0; i < totalFrames; i++) {
                BufferedImage image = createTestFrame(width, height, i, totalFrames);
                recorder.record(converter.convert(image));

                if (i % 5 == 0 || i == totalFrames - 1) {
                    System.out.printf("  进度: %d/%d 帧 (%.1f%%)\n", 
                            i + 1, totalFrames, (i + 1) * 100.0 / totalFrames);
                }
            }

        } finally {
            if (recorder != null) {
                try {
                    recorder.stop();
                    recorder.release();
                } catch (Exception e) {
                    // ignore
                }
            }
            converter.close();
        }
    }

    /**
     * 创建测试帧
     */
    private static BufferedImage createTestFrame(int width, int height, int frameIndex, int totalFrames) {
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = image.createGraphics();

        // 颜色渐变
        float progress = (float) frameIndex / totalFrames;
        Color startColor = Color.BLUE;
        Color endColor = Color.CYAN;
        int r = (int) (startColor.getRed() + (endColor.getRed() - startColor.getRed()) * progress);
        int g = (int) (startColor.getGreen() + (endColor.getGreen() - startColor.getGreen()) * progress);
        int b = (int) (startColor.getBlue() + (endColor.getBlue() - startColor.getBlue()) * progress);

        g2d.setColor(new Color(r, g, b));
        g2d.fillRect(0, 0, width, height);

        // 添加文字
        g2d.setColor(Color.WHITE);
        g2d.setFont(new Font("Arial", Font.BOLD, 36));
        String text = String.format("Frame %d/%d", frameIndex + 1, totalFrames);
        FontMetrics fm = g2d.getFontMetrics();
        int textWidth = fm.stringWidth(text);
        g2d.drawString(text, (width - textWidth) / 2, height / 2);

        g2d.dispose();
        return image;
    }
}
