package com.artfess.file.util;

import org.artofsolving.jodconverter.office.OfficeException;
import org.jodconverter.local.LocalConverter;
import org.jodconverter.local.office.LocalOfficeManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.io.File;
import java.util.Arrays;

/**
 * 创建文件转换器
 *
 * @company 阿特菲斯信息技术有限公司
 * @author:lj
 * @date:2018年6月15日
 */
@Component
public class LibreOfficeConverterUtils {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Value("${file.office.home}")
    private String officeHome;

    @Value("${file.office.enable:false}")
    private boolean fileEnable;

    @Value("${file.office.port:9693}")
    private String officePorts;

    private LocalOfficeManager officeManager;

    @PostConstruct
    public void startOfficeManager() {
        if (fileEnable && officeHome != null && !officeHome.isEmpty()) {
            logger.info("开始注入officeManager,{}", officeHome);

            int[] officePortList = Arrays.stream(officePorts.split(","))
                    .mapToInt(Integer::parseInt)
                    .toArray();

            officeManager = LocalOfficeManager.builder()
                    .officeHome(officeHome)
                    .portNumbers(officePortList)
                    .build();
            try {
                officeManager.start();
                logger.info("OfficeManager启动成功");
            } catch (OfficeException | org.jodconverter.core.office.OfficeException e) {
                throw new RuntimeException("启动OfficeManager失败", e);
            }
        }
    }

    public void convert(File inputFile, File outputFile) {
        if (officeManager == null) {
            throw new RuntimeException("OfficeManager未启动");
        }
        try {
            LocalConverter.make(officeManager)
                    .convert(inputFile)
                    .to(outputFile)
                    .execute();
            logger.info("转换成功");
        } catch (OfficeException | org.jodconverter.core.office.OfficeException e) {
            throw new RuntimeException("转换失败", e);
        }
    }

    @PreDestroy
    public void stopOfficeManager() {
        if (officeManager != null) {
            try {
                officeManager.stop();
                logger.info("OfficeManager停止成功");
            } catch (OfficeException | org.jodconverter.core.office.OfficeException e) {
                logger.error("停止OfficeManager失败", e);
            }
        }
    }
}

