package com.axis.innovators.box.util;

import java.io.IOException;

/**
 * 文件扩展名管理器
 * @author tzdwindows 7
 */
public class FileAssociationManager {
    /**
     * 将指定的文件扩展名与程序关联
     * @param extension 文件扩展名，例如 ".txt"
     */
    public static void associateFileExtension(String extension) throws IOException {
        associateProgramWithExtension(extension, System.getProperty("user.dir") + "\\toolbox.exe");
    }

    /**
     * 将指定的程序与文件扩展名关联
     *
     * @param extension 文件扩展名，例如 ".txt"
     * @param programPath 程序的完整路径，例如 "C:\\Program Files\\Notepad++\\notepad++.exe"
     * @throws IOException 如果关联失败时抛出异常
     */
    private static void associateProgramWithExtension(String extension, String programPath) throws IOException {
        String os = System.getProperty("os.name").toLowerCase();

        if (os.contains("win")) {
            String command = "assoc " + extension + "=MyFileType";
            Runtime.getRuntime().exec(command);
            command = "ftype MyFileType=\"" + programPath + "\" \"%1\"";
            Runtime.getRuntime().exec(command);
        } else if (os.contains("mac")) {
            String command = "duti -s " + programPath + " " + extension + " all";
            Runtime.getRuntime().exec(command);
        } else if (os.contains("nix") || os.contains("nux") || os.contains("aix")) {
            String command = "xdg-mime default " + programPath + " " + extension;
            Runtime.getRuntime().exec(command);
        } else {
            throw new UnsupportedOperationException("Unsupported operating system: " + os);
        }
    }
}