package com.artfess.file.util;

import com.artfess.file.extend.ControlDocumentFormatRegistry;
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 javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.io.File;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

/**
 * 创建文件转换器
 * @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:true}")
	boolean fileEnable;

	@Value("${file.office.port:9093}")
	Integer officePortNumber;

	OfficeManager officeManager;

	@PostConstruct
	public void initOfficeManager() {
		DefaultOfficeManagerConfiguration configuration = new DefaultOfficeManagerConfiguration();
		File file=new File(officeHome);
		if(file.exists() && fileEnable){
			logger.info(String.format("正在初始化openoffice组件：%s", officeHome));
			configuration.setOfficeHome(officeHome);
			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();
		}
	}
}
