package com.backendsys.utils;

import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.FrameGrabber;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.time.Duration;
import java.time.LocalDateTime;
import cn.hutool.core.date.DateUtil;

public class AudioUtils {


    /**
     * 获得远程音频的时长 (下载时间过长，暂时不使用)
     */
    public static String getRemoteVideoDuration(String remoteUrl) throws IOException {
        File localFile = downloadRemoteFile(remoteUrl);
        double duration = 0;
        try (FFmpegFrameGrabber frameGrabber = new FFmpegFrameGrabber(localFile)) {
            frameGrabber.start();
            //System.out.println(frameGrabber.getLengthInTime()/1000000);
            duration = frameGrabber.getLengthInTime()/1000000;
            frameGrabber.stop();
        } catch (FrameGrabber.Exception e) {
            e.printStackTrace();
        }
        return String.valueOf(duration);
    }

    /**
     * 下载文件到本地
     */
    private static File downloadRemoteFile(String remoteUrl) throws IOException {
        URL url = new URL(remoteUrl);
        HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
        int responseCode = httpConn.getResponseCode();

        // 检查HTTP响应代码是否为200
        if (responseCode == HttpURLConnection.HTTP_OK) {
            String contentType = httpConn.getContentType();
            InputStream inputStream = httpConn.getInputStream();
            if (contentType.startsWith("audio/")) {
                // 获取文件名，这里简单地从URL中获取，可能需要更复杂的逻辑
                String filename = remoteUrl.substring(remoteUrl.lastIndexOf('/') + 1);
                File localFile = new File(filename);
                Files.copy(inputStream, localFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
                return localFile;
            } else {
                throw new IOException("Unsupported content type: " + contentType);
            }
        } else {
            throw new IOException("Failed to download file from " + remoteUrl + ": " + responseCode);
        }
    }
}
