package com.artfess.file.util;

import java.io.File;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.artofsolving.jodconverter.OfficeDocumentConverter;
import org.artofsolving.jodconverter.office.DefaultOfficeManagerConfiguration;
import org.artofsolving.jodconverter.office.OfficeManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.artfess.file.extend.ControlDocumentFormatRegistry;

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

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

	@Value("${file.office.port:9193}")
	String officePortNumber;

	OfficeManager officeManager;

	@PostConstruct
	public void initOfficeManager() {
		fileEnable = false; // openOffice和libreOffice只能用一个 这里关闭openOffice
		DefaultOfficeManagerConfiguration configuration = new DefaultOfficeManagerConfiguration();
		File file=new File(officeHome);
		if(file.exists() && fileEnable){
			logger.info(String.format("正在初始化openoffice组件：%s", officeHome));
			configuration.setOfficeHome(officeHome);
			// 支持多个端口
			String[] portsArray = officePortNumber.split(",");
			int[] ports = new int[portsArray.length];
			for (int i = 0; i < portsArray.length; i++) {
				ports[i] = Integer.parseInt(portsArray[i].trim());
			}
			configuration.setPortNumbers(ports); // 开启多个端口
			configuration.setTaskExecutionTimeout(60000L); // 任务执行超时 60 秒
			configuration.setTaskQueueTimeout(30000L);     // 任务排队等待超时
			configuration.setMaxTasksPerProcess(10);       // 每个进程最多执行 10 个任务后重启
//			configuration.setPortNumber(officePortNumber);
			officeManager = configuration.buildOfficeManager();
			officeManager.start();
			logger.info("openoffice初始化完成.");
		}
	}

	public OfficeDocumentConverter getDocumentConverter() {
		OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager, new ControlDocumentFormatRegistry());

		converter.setDefaultLoadProperties(getLoadProperties());
		return converter;
	}

	private Map<String,?> getLoadProperties() {
		Map<String,Object> loadProperties = new HashMap<>(10);
		loadProperties.put("Hidden", true);
		loadProperties.put("ReadOnly", true);

		loadProperties.put("CharacterSet", Charset.forName("UTF-8").name());
		return loadProperties;
	}

	@PreDestroy
	public void destroyOfficeManager(){
		if (null != officeManager && officeManager.isRunning()) {
			officeManager.stop();
		}
	}
}
