package shop.alien.util.common;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@Configuration
public class FileUpload {

    @Value("${spring.web.resources.static-locations}")
    private String uploadDir;

    public String saveImage(MultipartFile image) {
        try {
            String cleanUploadDir = uploadDir.replace("file:///", "").replace("\\", "/");
            Path path = Paths.get(cleanUploadDir, image.getOriginalFilename());
            Files.createDirectories(path.getParent());
            Files.write(path, image.getBytes());
            return image.getOriginalFilename();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

//    public String getVideoDuration(MultipartFile image) {
//        String cleanUploadDir = uploadDir.replace("file:///", "").replace("\\", "/");
//        Path path = Paths.get(cleanUploadDir, image.getOriginalFilename());
//        try (FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(path.toString())) {
//            String fileExtension = getFileExtension(path.toString());
//            if ("mp4".equalsIgnoreCase(fileExtension)) {
//                grabber.setFormat("mp4");
//            } else if ("avi".equalsIgnoreCase(fileExtension)) {
//                grabber.setFormat("avi");
//            } else if ("mkv".equalsIgnoreCase(fileExtension)) {
//                grabber.setFormat("matroska");
//            }
//            grabber.start();
//            double durationInSeconds = grabber.getLengthInTime() / 1_000_000.0;
//            grabber.stop();
//            long hours = (long) durationInSeconds / 3600;
//            long minutes = (long) (durationInSeconds % 3600) / 60;
//            long seconds = (long) (durationInSeconds % 60);
//            return String.format("%dh %dm %ds", hours, minutes, seconds);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return "获取时长失败";
//        }
//    }

//    private String getFileExtension(String filePath) {
//        File file = new File(filePath);
//        String name = file.getName();
//        int lastIndexOfDot = name.lastIndexOf('.');
//        return (lastIndexOfDot == -1) ? "" : name.substring(lastIndexOfDot + 1);
//    }
}
