package cn.report.pdf.converter;

import java.io.IOException;
import java.util.Properties;

import org.jodconverter.core.office.OfficeManager;
import org.jodconverter.local.office.LocalOfficeManager;
import org.springframework.core.io.support.PropertiesLoaderUtils;


public class OfficeManagerInstance 
{
    private static OfficeManager INSTANCE = null;

    public static synchronized void start() {
        officeManagerStart();
    }
 
    public void init() {
        try {
            Properties properties = PropertiesLoaderUtils.loadAllProperties("libre.properties");
            String[] portNumbers = properties.getProperty("portNumbers", "").split(",");
            int[] ports = new int[portNumbers.length];

            for (int i = 0; i < portNumbers.length; i++) {
                ports[i] = Integer.parseInt(portNumbers[i]);
            }

            LocalOfficeManager.Builder builder = LocalOfficeManager.builder().install();
            builder.officeHome(properties.getProperty("libreOfficeHome", ""));
           
            builder.portNumbers(ports);
            builder.taskExecutionTimeout((long) (Integer.parseInt(properties.getProperty("taskExecutionTimeoutMinutes", "")) * 1000 * 60)); // minute
            builder.taskQueueTimeout((long) (Integer.parseInt(properties.getProperty("taskQueueTimeoutHours", "")) * 1000 * 60 * 60)); // hour

            INSTANCE = builder.build();
            officeManagerStart();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void officeManagerStart() {
        if (INSTANCE.isRunning()) {
            return;
        }

        try {
            INSTANCE.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}