package cn.reghao.oss.store.util;

import cn.reghao.jutil.jdk.shell.Shell;
import cn.reghao.oss.storeapi.constant.ObjectType;
import cn.reghao.oss.storeapi.constant.VideoUrlType;
import org.apache.tika.Tika;
import org.apache.tika.metadata.Metadata;

import java.io.FileInputStream;

/**
 * @author reghao
 * @date 2023-06-12 22:47:06
 */
public class FileType {
    private final static Tika tika = new Tika();

    public static String getMediaType1(String src) {
        String cmd = String.format("/bin/file -b --mime-type \"%s\"", src);
        return Shell.execWithResult(cmd);
    }

    public static String getMediaType(String src) {
        try {
            FileInputStream fis = new FileInputStream(src);
            Metadata metadata = new Metadata();
            tika.parse(fis, metadata);
            String mediaType = metadata.get("Content-Type");
            if (mediaType != null) {
                return mediaType;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "application/octet-stream";
    }

    public static int getFileType(String contentType) {
        int fileType = ObjectType.Other.getCode();
        if (contentType == null) {
            return fileType;
        } else if (contentType.startsWith("image")) {
            fileType = ObjectType.Image.getCode();
        } else if (contentType.startsWith("video")) {
            fileType = ObjectType.Video.getCode();
        } else if (contentType.startsWith("audio")) {
            fileType = ObjectType.Audio.getCode();
        } else if (contentType.startsWith("text")) {
            fileType = ObjectType.Text.getCode();
        }
        return fileType;
    }

    public static String getVideoUrlType(String src) {
        String mediaType = getMediaType(src);
        String urlType = VideoUrlType.mp4.name();
        if (mediaType.endsWith("flv")) {
            urlType = VideoUrlType.flv.name();
        }

        return urlType;
    }
}
