package com.qmth.qrzk.repository.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Scanner;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import net.arnx.wmf2svg.gdi.svg.SvgGdi;
import net.arnx.wmf2svg.gdi.svg.SvgGdiException;
import net.arnx.wmf2svg.gdi.wmf.WmfParseException;
import net.arnx.wmf2svg.gdi.wmf.WmfParser;

import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;

public class Wmf2Png {
	
	private static final Logger log = Logger.getLogger(Wmf2Png.class);
	
	public static void main(String[] args) throws Exception {
//		System.out.println(new String(General.getImageByteArr(new File("D:/qrzk/tmp/3.svg"))));
//		File emf = new File("E:/temp/doc/1.emf");
//		File png = new File(emf.getAbsolutePath() + ".png");
//		emf2Png(emf, png);

		File wmf = new File("D:/tmp/wmf/image9.wmf");
		File svg = new File(wmf.getAbsolutePath() + ".xml");
		wmf2Svg(wmf, svg);
		
//		png.renameTo(newPng);
//		System.out.println(newPng.getAbsolutePath());
		// System.out.println((20 / (21 * 1.0)));
		// svgToPng("F:\\SVN\\BobUtil\\web\\25177.svg", "F:\\SVN\\BobUtil\\web\\25177.png");
	}

	/**
	 * 将wmf转换为svg
	 * 
	 * @param wmfFile
	 * @param svgFile
	 * @throws SvgGdiException 
	 * @throws WmfParseException 
	 * @throws IOException 
	 * @throws TransformerException 
	 */
	public static void wmf2Svg(File wmfFile, File svgFile) throws SvgGdiException, IOException, WmfParseException, TransformerException {
		boolean compatible = false;
		InputStream wmfIn = null;
		OutputStream svgOut = null;
		try {
//			FileUtils.copyFile(wmfFile, new File(wmfFile.getPath() + ".wmf"));
			wmfIn = new FileInputStream(wmfFile);
			WmfParser parser = new WmfParser();
			final SvgGdi gdi = new SvgGdi(compatible);
			parser.parse(wmfIn, gdi);

			Document doc = gdi.getDocument();
			svgOut = new FileOutputStream(svgFile);
			output(doc, svgOut);
		}finally{
			General.close(svgOut);
			General.close(wmfIn);
		}
	}

	/**
	 * 将emf转换为svg
	 * <p><b>*当前freehep-graphicsio V2.1.1版本对复杂的emf文件无法正常转换成png</b></p>
	 * @param emfFile
	 * @param pngFile
	 * @throws IOException 
	 */
	public static void emf2Png(File emfFile, File pngFile) throws IOException{
		String cmd = ParamUtils.Emf2PngExePath + " " + emfFile.getAbsolutePath() + " png " + pngFile.getAbsolutePath();
		try {
			long cur = System.currentTimeMillis();
			Process p = Runtime.getRuntime().exec(cmd);
			while(p.isAlive() && (System.currentTimeMillis() - cur) < 1000){
				Thread.sleep(2);
			}
//			System.out.println(p.isAlive());
			if(p.isAlive()){
				p.destroy();
			}
		} catch (Exception e) {
			log.warn("执行emf转png的程序(命令行：" + cmd + ")失败，原因：" + e.getMessage(), e);;
		}
	}

	/**
	 * @Description: 输出svg文件
	 * @param doc
	 * @param out
	 * @throws TransformerException 
	 * @throws IOException 
	 * @throws Exception
	 *             设定文件
	 */
	private static void output(Document doc, OutputStream out) throws TransformerException, IOException{
		TransformerFactory factory = TransformerFactory.newInstance();
		Transformer transformer = factory.newTransformer();
		transformer.setOutputProperty(OutputKeys.METHOD, "xml");
		transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
		transformer.setOutputProperty(OutputKeys.INDENT, "yes");
//		transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "-//W3C//DTD SVG 1.0//EN");
//		transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd");
		transformer.transform(new DOMSource(doc), new StreamResult(out));
		out.flush();
	}

	/**
	 * @Description:对svg文件做预处理(这里主要是调整大小，先缩小10倍，如果还大于默认值，则按比例缩小)
	 * @param svgFile
	 * @throws IOException 
	 * @throws ParserConfigurationException 
	 * @throws SAXException 
	 * @throws TransformerException 
	 *             设定文件
	 */
	public static void preprocessSvgFile(File svgFile) throws IOException, ParserConfigurationException, SAXException, TransformerException{
		FileInputStream svgIn = null;
		Scanner sc = null;
		ByteArrayOutputStream os = null;
		byte[] osByteArr = null;
		
		int defaultWeight = 400;// 默认宽度
		try{
			svgIn = new FileInputStream(svgFile);
			os = new ByteArrayOutputStream();
			sc = new Scanner(svgIn, "UTF-8");
			while (sc.hasNextLine()) {
				String ln = sc.nextLine();
				if (!ln.startsWith("<!DOCTYPE")) {
					os.write((ln + "\r\n").getBytes());
				}
			}
			os.flush();
			osByteArr = os.toByteArray();
		}finally{
			General.close(os);
			General.close(sc);
			General.close(svgIn);
		}
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();
		Document doc = null;
		doc = builder.parse(new ByteArrayInputStream(osByteArr));
		try {
			doc = builder.parse(new ByteArrayInputStream(osByteArr));
		} catch (Exception e) {
			try{
				svgIn = new FileInputStream(svgFile);
				os = new ByteArrayOutputStream();
				IOUtils.copyLarge(svgIn, os);
				osByteArr = os.toByteArray();
				doc = builder.parse(new ByteArrayInputStream(osByteArr));
			} finally {
				General.close(os);
				General.close(svgIn);
			}
		}
		
		int height = Integer.parseInt(((Element) doc.getElementsByTagName("svg").item(0)).getAttribute("height"));
		int width = Integer.parseInt(((Element) doc.getElementsByTagName("svg").item(0)).getAttribute("width"));
		int newHeight = height;// 新高
		int newWidth = width;// 新宽
//		newHeight = height / 10;// 高缩小10倍
//		newWidth = width / 10; // 宽缩小10倍
		// 如果缩小10倍后宽度还比defaultHeight大，则进行调整
		if (newWidth > defaultWeight) {
			newWidth = defaultWeight;
			newHeight = defaultWeight * height / width;
		}

		((Element) doc.getElementsByTagName("svg").item(0)).setAttribute("width", String.valueOf(newWidth));
		((Element) doc.getElementsByTagName("svg").item(0)).setAttribute("height", String.valueOf(newHeight));
		
		OutputStream svgOut = null;
		try{
			svgOut = new FileOutputStream(svgFile);
			output(doc, svgOut);
		}finally{
			General.close(svgOut);
		}
	}
}
