package com.platform.modules.plm.util;

import com.platform.modules.plm.entity.PlmChunkEntity;
import it.sauronsoftware.jave.Encoder;
import it.sauronsoftware.jave.MultimediaInfo;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
import java.util.stream.Stream;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import com.platform.common.utils.FileUtils;

/**
 * 获取视频播放的时长
 *
 * @author yikaihong
 */
@ConfigurationProperties(prefix = "materia")
@Component
@Slf4j
public class MaterialUtils {

	public static String getMaterialUrl(String src, String urlPath) {
		if(StringUtils.isBlank(src) || StringUtils.isBlank(urlPath))
			return src;
		src.trim();
		if(src.startsWith("http")) {
			return src;
		}
		if(!src.startsWith("/"))
			src = "/" + src;
		if(urlPath.endsWith("/"))
			urlPath = urlPath.substring(0, urlPath.length() - 1);
		return urlPath + src;
	}
	
	public static Long getPlayTime(String materialPath) {
		if (StringUtils.isEmpty(materialPath)) {
            return null;
        }
        File file = new File(materialPath);
        if (!file.exists()) {
            return null;
        }
        // 文件后缀校验
        if (!VideoTypeEnum.isVideo(FileUtils.getSuffix(file)) && !AudioTypeEnum.isAudio(FileUtils.getSuffix(file))) {
            return null;
        }

        Encoder encoder = new Encoder();
        MultimediaInfo info = null;
        try {
            info = encoder.getInfo(file);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (info == null) {
            return null;
        }
        long longTime = info.getDuration();
        return longTime;
	}
	
    /**
     * 获取视频的播放时间
     *
     * @param videoPath
     * @param pattern
     * @return
     */
    public static String getPlayTime(String materialPath, String pattern) {
        if (StringUtils.isEmpty(materialPath)) {
            return null;
        }
//        if (StringUtils.isEmpty(pattern)) {
//            pattern = NUMBER_PATTERN;
//        }
        File file = new File(materialPath);
        if (!file.exists()) {
            return null;
        }
        // 文件后缀校验
        if (!VideoTypeEnum.isVideo(FileUtils.getSuffix(file)) && !AudioTypeEnum.isAudio(FileUtils.getSuffix(file))) {
            return null;
        }

        Encoder encoder = new Encoder();
        MultimediaInfo info = null;
        try {
            info = encoder.getInfo(file);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (info == null) {
            return null;
        }
        long longTime = info.getDuration();
//      long longTime = info.getDuration() / 1000;
//      int hour = (int) (longTime / 3600);
//      int minute = (int) (longTime % 3600) / 60;
//      int second = (int) (longTime - hour * 3600 - minute * 60);
//      String result = DecimalFormatUtils.numberFormat(pattern, hour)
//              + SEMICOLON + DecimalFormatUtils.numberFormat(pattern, minute)
//              + SEMICOLON + DecimalFormatUtils.numberFormat(pattern, second);

        return FileCalculateUtils.calculateFilePlayTimeString(longTime);
    }
    
    public static Long getPlayTime(File file) {
    	if (file == null) {
            return null;
        }
        if (!file.exists()) {
            return null;
        }
        // 文件后缀校验
        if (!VideoTypeEnum.isVideo(FileUtils.getSuffix(file)) && !AudioTypeEnum.isAudio(FileUtils.getSuffix(file))) {
            return null;
        }
        Encoder encoder = new Encoder();
        MultimediaInfo info = null;
        try {
            info = encoder.getInfo(file);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (info == null) {
            return null;
        }
        long longTime = info.getDuration();
        return longTime;
	}

    /**
     * 获取视频的播放时间
     *
     * @param file
     * @param pattern
     * @return
     */
    public static String getPlayTime(File file, String pattern) {
        if (file == null) {
            return null;
        }
//        if (StringUtils.isEmpty(pattern)) {
//            pattern = NUMBER_PATTERN;
//        }
        if (!file.exists()) {
            return null;
        }
        // 文件后缀校验
        if (!VideoTypeEnum.isVideo(FileUtils.getSuffix(file)) && !AudioTypeEnum.isAudio(FileUtils.getSuffix(file))) {
            return null;
        }
        Encoder encoder = new Encoder();
        MultimediaInfo info = null;
        try {
            info = encoder.getInfo(file);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (info == null) {
            return null;
        }
        long longTime = info.getDuration();
//        long longTime = info.getDuration() / 1000;
//        int hour = (int) (longTime / 3600);
//        int minute = (int) (longTime % 3600) / 60;
//        int second = (int) (longTime - hour * 3600 - minute * 60);
//        String result = DecimalFormatUtils.numberFormat(pattern, hour)
//                + SEMICOLON + DecimalFormatUtils.numberFormat(pattern, minute)
//                + SEMICOLON + DecimalFormatUtils.numberFormat(pattern, second);
        return FileCalculateUtils.calculateFilePlayTimeString(longTime);
    }
    
    public static Long getFileSize(String materialPath) {
    	if (StringUtils.isEmpty(materialPath)) {
            return null;
        }
        File file = new File(materialPath);
        if (!file.exists()) {
            return null;
        }
        // 文件后缀校验
        if (!VideoTypeEnum.isVideo(FileUtils.getSuffix(file)) && !AudioTypeEnum.isAudio(FileUtils.getSuffix(file))) {
            return null;
        }
        long fileSize = file.length();
        return fileSize;
	}

    /**
     * 计算文件块儿大小
     *
     * @param videoPath
     * @return
     */
    public static String getFileSize(String materialPath, FileSizeUnitEnum unitEnum) {
        if (StringUtils.isEmpty(materialPath)) {
            return null;
        }
        File file = new File(materialPath);
        if (!file.exists()) {
            return null;
        }
        // 文件后缀校验
        if (!VideoTypeEnum.isVideo(FileUtils.getSuffix(file)) && !AudioTypeEnum.isAudio(FileUtils.getSuffix(file))) {
            return null;
        }
        long fileSize = file.length();
        return FileCalculateUtils.calculateFileSizeString(fileSize,
                unitEnum);
    }
    
    public static Long getFileSize(File file) {
    	 if (!file.exists()) {
             return null;
         }
         // 文件后缀校验
         if (!VideoTypeEnum.isVideo(FileUtils.getSuffix(file)) && !AudioTypeEnum.isAudio(FileUtils.getSuffix(file)) && !ImageTypeEnum.isImage(FileUtils.getSuffix(file))) {
             return null;
         }
         long fileSize = file.length();
        return fileSize;
	}

    /**
     * 计算文件块儿大小
     *
     * @param file
     * @param unitEnum
     * @return
     */
    public static String getFileSize(File file, FileSizeUnitEnum unitEnum) {
        if (!file.exists()) {
            return null;
        }
        // 文件后缀校验
        if (!VideoTypeEnum.isVideo(FileUtils.getSuffix(file)) && !AudioTypeEnum.isAudio(FileUtils.getSuffix(file)) && !ImageTypeEnum.isImage(FileUtils.getSuffix(file))) {
            return null;
        }
        long fileSize = file.length();
        return FileCalculateUtils.calculateFileSizeString(fileSize,
                unitEnum);
    }

    /**
     * 时间目录
     *
     * @return
     */
    public static String getDateDir() {
        DateFormat bf = new SimpleDateFormat("yyyyMMdd");
        Date currentDate = new Date();
        return bf.format(currentDate);
    }

    /**
     * 分块文件生成路径
     * @param uploadFolder
     * @param chunk
     * @return
     */
    public static String generatePath(String uploadFolder, PlmChunkEntity chunk) {
        StringBuilder sb = new StringBuilder();
        sb.append(uploadFolder).append("/").append(chunk.getIdentifier());
        //判断uploadFolder/identifier 路径是否存在，不存在则创建
        if (!Files.isWritable(Paths.get(sb.toString()))) {
            log.info("path not exist,create path: {}", sb.toString());
            try {
                Files.createDirectories(Paths.get(sb.toString()));
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
        }

        return sb.append("/")
                .append(chunk.getFilename())
                .append("-")
                .append(chunk.getChunkNumber()).toString();
    }

    /**
     * 文件合并
     *
     * @param targetFile
     * @param folder
     */
    public static void merge(String targetFile, String folder, String filename) throws IOException {
        Path localFile = Paths.get(targetFile);
        if (Files.exists(localFile)) {
            String bakFile = localFile.getParent().toString() + UUID.randomUUID().toString() + "-" + filename;
            Files.move(localFile, Paths.get(bakFile));
        }
        if (Files.notExists(localFile.getParent())) {
            Files.createDirectory(localFile.getParent());
        }
        Files.createFile(localFile);
        Stream<Path> stream = Files.list(Paths.get(folder));
        stream.filter(path -> !path.getFileName().toString().equals(filename))
                .sorted((o1, o2) -> {
                    String p1 = o1.getFileName().toString();
                    String p2 = o2.getFileName().toString();
                    int i1 = p1.lastIndexOf("-");
                    int i2 = p2.lastIndexOf("-");
                    return Integer.valueOf(p2.substring(i2)).compareTo(Integer.valueOf(p1.substring(i1)));
                })
                .forEach(path -> {
                    try {
                        //以追加的形式写入文件
                        Files.write(Paths.get(targetFile), Files.readAllBytes(path), StandardOpenOption.APPEND);
                        //合并后删除该块
                        Files.delete(path);
                    } catch (IOException e) {
                        log.error(e.getMessage(), e);
                    }
                });
        // 必须要关闭，否则无法释放
        stream.close();
    }
    
    public static void main(String[] args) {
		
	}

}
