package com.testor.common.util;

import java.net.URL;
import java.util.HashMap;
import java.util.Map;

public class MimeTypeUtil {

    // MIME类型映射表
    private static final Map<String, String> EXTENSION_TO_MIME_TYPE = new HashMap<>();

    static {
        EXTENSION_TO_MIME_TYPE.put("png", "image/png");
        EXTENSION_TO_MIME_TYPE.put("jpg", "image/jpeg");
        EXTENSION_TO_MIME_TYPE.put("jpeg", "image/jpeg");
        EXTENSION_TO_MIME_TYPE.put("gif", "image/gif");
        EXTENSION_TO_MIME_TYPE.put("bmp", "image/bmp");
        EXTENSION_TO_MIME_TYPE.put("webp", "image/webp");
        EXTENSION_TO_MIME_TYPE.put("svg", "image/svg+xml");
        EXTENSION_TO_MIME_TYPE.put("pdf", "application/pdf");
        EXTENSION_TO_MIME_TYPE.put("txt", "text/plain");
        EXTENSION_TO_MIME_TYPE.put("html", "text/html");
        EXTENSION_TO_MIME_TYPE.put("json", "application/json");
        EXTENSION_TO_MIME_TYPE.put("xml", "application/xml");
        // 可以根据需要继续扩展
    }

    /**
     * 根据 URL 链接的后缀获取 MIME 类型
     *
     * @param url 链接
     * @return 对应的 MIME 类型，如果无法识别则返回 "application/octet-stream"
     */
    public static String getMimeTypeFromUrl(String url) {
        try {
            // 获取文件扩展名
            String fileExtension = getFileExtension(url);
            if (fileExtension != null && EXTENSION_TO_MIME_TYPE.containsKey(fileExtension)) {
                return EXTENSION_TO_MIME_TYPE.get(fileExtension);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "application/octet-stream"; // 默认值，表示二进制流
    }

    /**
     * 从 URL 中获取文件扩展名
     *
     * @param url URL 链接
     * @return 文件扩展名
     */
    private static String getFileExtension(String url) {
        try {
            // 解析 URL 获取文件名部分
            URL parsedUrl = new URL(url);
            String path = parsedUrl.getPath();
            int dotIndex = path.lastIndexOf('.');
            if (dotIndex > -1 && dotIndex < path.length() - 1) {
                return path.substring(dotIndex + 1).toLowerCase(); // 返回文件扩展名小写
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        // 测试用例
        System.out.println(getMimeTypeFromUrl("https://example.com/images/pic1.png")); // image/png
        System.out.println(getMimeTypeFromUrl("https://example.com/docs/file.pdf")); // application/pdf
        System.out.println(getMimeTypeFromUrl("https://example.com/file.xyz")); // application/octet-stream
    }
}

