package CoreFS.SA05;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import CoreFS.SA01.CoreException;
import CoreFS.SA01.CoreGlobalConstants;
import java.io.FileOutputStream;


/**
 * @desc :文件操作类
 * @author sunjiawang
 * @create:091128
 * @modify:091128
 */
public class CoreFileOperation implements CoreIFileOperation {
	protected final Log log = LogFactory.getLog(getClass());
	private String  cfgpath = Thread.currentThread().getContextClassLoader().getResource("../cfgfiles").getPath() ;
	/**
	 * @DESC: 读取没行的配置内容 根据分隔的标识放入到MAP中
	 * @param srcpath
	 *            源文件地址
	 * @param splitFlag
	 *            分隔标识符
	 * @create:091128
	 * @modify:091128
	 * @return
	 */
	public Map ReadText(String srcpath, String splitFlag) {
		Map properties = new HashMap();
		BufferedReader br = null;
		FileReader fr = null;

		String myreadline;
		String mapKey = "";
		String mapValue = "";
		try {
			fr = new FileReader(srcpath);
			br = new BufferedReader(fr); // 缓冲指定文件的输入
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}// 创建FileReader对象，用来读取字符流
		try {
			while (br.ready()) {
				myreadline = br.readLine();// 读取一行
				String[] linecontent = myreadline.split(splitFlag);
				mapKey = linecontent[0].trim();
				mapValue = linecontent[1].trim();
				properties.put(mapKey, mapValue);
				System.out.println(myreadline);// 在屏幕上输出
			}
			br.close();
			fr.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return properties;

	}

	/**
	 * @DESC: 读取每行的配置内容 根据分隔的标识放入到MAP中
	 * @param srcpath
	 *            源文件地址
	 * @param splitFlag
	 *            分隔标识符
	 * @create:091128
	 * @modify:091128
	 * @return
	 * @throws ParserConfigurationException
	 * @throws IOException
	 * @throws SAXException
	 */
	public String ReadText(String srcpath) {
		String str = "";
		try {
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder = dbf.newDocumentBuilder();
			Document doc = builder.parse(srcpath);
			//doc.setXmlStandalone(false);
			//doc.setXmlVersion("");

			
			if (doc.getChildNodes().getLength()>1)
			{
				doc.removeChild(doc.getFirstChild());
			}
			StringWriter sw = new StringWriter();
           
			Transformer serializer = TransformerFactory.newInstance()
					.newTransformer();
			serializer.transform(new DOMSource(doc), new StreamResult(sw));
			
			str = sw.toString();

		} catch (Exception ex) {

		}

		return str;

		// BufferedReader br = null;
		// FileReader fr = null;
		// StringBuffer sb = new StringBuffer();
		//
		// String myreadline = null;
		// try {
		// fr = new FileReader(srcpath);
		// String str = fr.getEncoding();
		// br = new BufferedReader(fr); // 缓冲指定文件的输入
		// } catch (FileNotFoundException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }// 创建FileReader对象，用来读取字符流
		// try {
		// while (br.ready()) {
		// myreadline = br.readLine();// 读取一行;
		// sb.append(myreadline);
		// // System.out.println(myreadline);// 在屏幕上输出
		// }
		// br.close();
		// fr.close();
		// } catch (IOException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }
		// return this.codeToString(sb.toString());

	}
	public Document ReadTextToXml(String srcpath) {

		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		Document doc = null;
		try {
			DocumentBuilder builder = dbf.newDocumentBuilder();
			doc = builder.parse(srcpath);			
		} catch (Exception ex) {
			doc = null;
		}
		return doc;
	}

	/**
	 * 
	 * @param srcpath
	 *            源路径
	 * @return
	 */

	/**
	 * 
	 * @param srcpath
	 *            源文件地址
	 * @param parNode
	 *            XML的父结点
	 * @param args
	 *            子结点名
	 * @create:091128
	 * @modify:091128
	 * @return
	 */
	public List<String> ReadXml(String srcpath, String parNode, String[] args) {
		List ls = new ArrayList();
		DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
				.newInstance();
		DocumentBuilder docBuilder;
		Document doc = null;
		Map map = null;
		try {
			docBuilder = docBuilderFactory.newDocumentBuilder();
			try {
				doc = docBuilder.parse(new File(srcpath));
				doc.getDocumentElement().normalize();
			} catch (SAXException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.println("Root element of the doc is "
					+ doc.getDocumentElement().getNodeName());
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		NodeList dbList = doc.getElementsByTagName(parNode);
		if (dbList != null && dbList.getLength() != 0) {
			for (int s = 0; s < dbList.getLength(); s++) {
				Node firstNode = dbList.item(s);
				if (firstNode.getNodeType() == Node.ELEMENT_NODE) {

					Element dbElement = (Element) firstNode;
					map = new HashMap();

					for (int i = 0; i < args.length; i++) {
						NodeList urlList = dbElement
								.getElementsByTagName(args[i]);
						Element urlElement = (Element) urlList.item(0);
						if (urlElement == null)
							break;
						NodeList texturlList = urlElement.getChildNodes();
						String value = (String) ((texturlList.item(0) == null) ? ""
								: ((Node) texturlList.item(0)).getNodeValue())
								.trim();
						System.out.println("args : " + args[i].toString()
								+ "  >>" + value);
						map.put(args[i].trim(), value);
					}
					ls.add(map);
				}// end of if clause

			}
		}
		return ls;

	}

	public List<String> delXmlById(String srcpath, String parNode,
			String[] args, String idname, String idvalue) {
		List ls = new ArrayList();
		DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
				.newInstance();
		DocumentBuilder docBuilder;
		Document doc = null;
		Map map = null;
		try {
			docBuilder = docBuilderFactory.newDocumentBuilder();
			try {
				doc = docBuilder.parse(new File(srcpath));
				doc.getDocumentElement().normalize();
			} catch (SAXException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.println("Root element of the doc is "
					+ doc.getDocumentElement().getNodeName());
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		NodeList dbList = doc.getElementsByTagName(parNode);
		for (int s = 0; s < dbList.getLength(); s++) {
			Node firstNode = dbList.item(s);
			if (firstNode.getNodeType() == Node.ELEMENT_NODE) {

				Element dbElement = (Element) firstNode;
				map = new HashMap();

				boolean addflag = false;
				for (int i = 0; i < args.length; i++) {
					NodeList urlList = dbElement.getElementsByTagName(args[i]);
					Element urlElement = (Element) urlList.item(0);

					NodeList texturlList = urlElement.getChildNodes();
					String value = (String) ((texturlList.item(0) == null) ? ""
							: ((Node) texturlList.item(0)).getNodeValue())
							.trim();
					System.out.println("args : " + args[i].toString() + "  >>"
							+ value);
					if (idvalue.equals(value) && args[i].equals(idname)) {
						addflag = false;
						break;
					} else {
						addflag = true;
						map.put(args[i].trim(), value);
					}
				}
				if (addflag) {
					ls.add(map);
				}
			}// end of if clause

		}

		return ls;

	}

	public List<String> updateXml(String srcpath, String parNode,
			String[] args, HashMap hm, String idname, String idvalue) {
		List ls = new ArrayList();
		DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
				.newInstance();
		DocumentBuilder docBuilder;
		Document doc = null;
		Map map = null;
		try {
			docBuilder = docBuilderFactory.newDocumentBuilder();
			try {
				doc = docBuilder.parse(new File(srcpath));
				doc.getDocumentElement().normalize();
			} catch (SAXException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.println("Root element of the doc is "
					+ doc.getDocumentElement().getNodeName());
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		NodeList dbList = doc.getElementsByTagName(parNode);
		for (int s = 0; s < dbList.getLength(); s++) {
			Node firstNode = dbList.item(s);
			if (firstNode.getNodeType() == Node.ELEMENT_NODE) {

				Element dbElement = (Element) firstNode;
				map = new HashMap();
				boolean updflag = false;
				int flgcnt = 0;
				for (int i = 0; i < args.length; i++) {
					NodeList urlList = dbElement.getElementsByTagName(args[i]);
					Element urlElement = (Element) urlList.item(0);

					NodeList texturlList = urlElement.getChildNodes();
					String value = (String) ((texturlList.item(0) == null) ? ""
							: ((Node) texturlList.item(0)).getNodeValue())
							.trim();
					System.out.println("args : " + args[i].toString() + "  >>"
							+ value);
					if (value.equals(idvalue) && args[i].equals(idname)) {
						updflag = true;
						flgcnt++;
					}
					if (updflag && flgcnt != 0) {
						value = (String) hm.get(args[i]);
					}
					map.put(args[i].trim(), value);
				}
				ls.add(map);
			}// end of if clause

		}

		return ls;

	}

	public List<String> ReadXml(String srcpath, String parNode, String[] args,
			boolean webflag) {
		if (webflag == true) {
			srcpath = this.getWebDir(srcpath);
		}
		return this.ReadXml(srcpath, parNode, args);
	}

	/**
	 * 
	 * @param srcpath
	 *            源文件地址
	 * @param parNode
	 *            XML的父结点
	 * @param args
	 *            子结点名
	 * @create:091128
	 * @modify:091128
	 * @return
	 */
	public List<String> ReadQueryXml(String srcpath, String parNode,
			String[] args, String[] quyparams, String[] quyvalues) {
		List ls = new ArrayList();
		String path = this.getWebDir(srcpath);
		DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
				.newInstance();
		DocumentBuilder docBuilder;
		Document doc = null;
		try {
			docBuilder = docBuilderFactory.newDocumentBuilder();
			try {
				doc = docBuilder.parse(new File(path));
				doc.getDocumentElement().normalize();
			} catch (SAXException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.println("Root element of the doc is "
					+ doc.getDocumentElement().getNodeName());
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		NodeList dbList = doc.getElementsByTagName(parNode);
		for (int s = 0; s < dbList.getLength(); s++) {
			Node firstNode = dbList.item(s);
			Map map = null;
			if (firstNode.getNodeType() == Node.ELEMENT_NODE) {
				boolean isfind = false;
				Element dbElement = (Element) firstNode;
				int m = 0;
				for (int j = 0; j < quyparams.length; j++) {
					NodeList urlList = dbElement
							.getElementsByTagName(quyparams[j]);
					Element urlElement = (Element) urlList.item(0);
					NodeList texturlList = urlElement.getChildNodes();
					String value = (String) ((texturlList.item(0) == null) ? ""
							: ((Node) texturlList.item(0)).getNodeValue())
							.trim();
					if (value.equals(quyvalues[j])) {
						m++;
						if (m == quyparams.length) {
							isfind = true;
						}

					} else {
						continue;
					}

				}
				if (isfind) {
					map = new HashMap();
					for (int i = 0; i < args.length; i++) {
						NodeList urlList = dbElement
								.getElementsByTagName(args[i]);
						Element urlElement = (Element) urlList.item(0);

						NodeList texturlList = urlElement.getChildNodes();
						String value = (String) ((texturlList.item(0) == null) ? ""
								: ((Node) texturlList.item(0)).getNodeValue())
								.trim();
						System.out.println("args : " + args[i].toString()
								+ "  >>" + value);
						map.put(args[i].trim(), value);
					}
				}

			}
			if (map != null) {
				ls.add(map);
			}
		}// end of if clause

		return ls;

	}

	public ArrayList<String> ReadQueryXml(String srcpath, String parNode,
			String[] args, HashMap paramMap, HashMap paramMapType) {
		ArrayList ls = new ArrayList();
		DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
				.newInstance();
		DocumentBuilder docBuilder;
		Document doc = null;

		try {
			docBuilder = docBuilderFactory.newDocumentBuilder();
			try {
				doc = docBuilder.parse(new File(srcpath));
				doc.getDocumentElement().normalize();
			} catch (SAXException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.println("Root element of the doc is "
					+ doc.getDocumentElement().getNodeName());
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		NodeList dbList = doc.getElementsByTagName(parNode);
		for (int s = 0; s < dbList.getLength(); s++) {
			Map map = null;
			Node firstNode = dbList.item(s);
			if (firstNode.getNodeType() == Node.ELEMENT_NODE) {

				Element dbElement = (Element) firstNode;
				int m = 0;
				boolean isfind = false;
				for (int j = 0; j < paramMap.size(); j++) {
					Set keyset = paramMap.keySet();
					Object[] keyarr = keyset.toArray();
					System.out.println(keyarr.length);
					for (int n = 0; n < keyarr.length; n++) {
						System.out.println("keyarr[n]  " + keyarr[n]);
					}

					NodeList urlList = dbElement.getElementsByTagName(keyarr[j]
							.toString());
					Element urlElement = (Element) urlList.item(0);

					NodeList texturlList = urlElement.getChildNodes();
					String value = (String) ((texturlList.item(0) == null) ? ""
							: ((Node) texturlList.item(0)).getNodeValue())
							.trim();
					// if (value.equals(paramMap.get(keyarr[j]))) {

					if (paramMapType.get(keyarr[j]).equals("1")) // 等于
					{
						if (value.equals(paramMap.get(keyarr[j]))) {
							m++;
							if (m == paramMap.size()) {
								isfind = true;
							}

						} else {
							break;
						}

					} else if (paramMapType.get(keyarr[j]).equals("2")) // 左右like
					{
						if (value.contains((CharSequence) paramMap
								.get(keyarr[j]))) {
							m++;
							if (m == paramMap.size()) {
								isfind = true;
							}

						} else {
							break;
						}
					}
				}
				if (paramMap.size() == 0) {
					isfind = true;
				}
				if (isfind) {
					map = new HashMap();
					for (int i = 0; i < args.length; i++) {
						NodeList urlList = dbElement
								.getElementsByTagName(args[i]);
						Element urlElement = (Element) urlList.item(0);

						NodeList texturlList = urlElement.getChildNodes();
						String value = (String) ((texturlList.item(0) == null) ? ""
								: ((Node) texturlList.item(0)).getNodeValue())
								.trim();
						System.out.println("args : " + args[i].toString()
								+ "  >>" + value);
						map.put(args[i].trim(), value);
					}

				}
				if (map != null) {
					ls.add(map);
				}
			}// end of if clause
		}

		return ls;

	}

	public String codeToString(String str) {
		String s = str;
		try {
			byte temp[] = s.getBytes("UTF-8");
			s = new String(temp);
			return s;
		} catch (Exception e) {
			return s;
		}
	}

	public static void main(String[] args) {
		CoreFileOperation test = new CoreFileOperation();
		// String strfile = test.ReadText("src/uam.core");
		// String tgtfile = test.codeToString(strfile);
		// System.out.println(strfile);
		// System.out.println(test.isFileExists(CoreGlobalConstants.ROLEBEAN_ABSOLUTXMLCONFIGPATH));
		// System.out.println(test.isFileContentNull(CoreGlobalConstants.ROLEBEAN_ABSOLUTXMLCONFIGPATH));
		// test.SaveAsXmlFiles("cfgfiles/1.xml", "xxxxxyyyy");
		System.out.println(System.getProperty("ContextTransService.java"));
	}

	public boolean isFileExists(String path) {
		File f = new File(path);
		if (!f.exists()) {
			String errMsg = "找不到对应的文件...";
			log.error(errMsg);
			throw new CoreException(errMsg);
		}
		return f.exists();
	}

	public boolean isFileContentNull(String path) {
		File f = new File(path);
		Long l = f.length();
		boolean contentIsNull = false;
		if (l == 0) {
			contentIsNull = true;
		} else {
			contentIsNull = false;
		}
		return contentIsNull;
	}

	public String getWebDir(String path) {

		String dir = CoreFileOperation.class.getClassLoader().getResource(path)
				.getPath();
		return dir;

	}

	public void SaveAsXmlFiles(String xmlfilename, String strXML) {
		String filePath = CoreGlobalConstants.ROLEBEAN_REMOTEXMLCONFIGPATH
				+ xmlfilename + ".xml";
		strXML = this.codeToString(strXML);
		if (!this.isFileExists(filePath)) {
			File f = new File(filePath);
		}
		PrintWriter pw = null;
		try {
			pw = new PrintWriter(new FileOutputStream(xmlfilename));
			pw.write(strXML);
			pw.flush();
			pw.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public void SaveDesignMainXml(String xmlfilename, String strXML) {
		String filePath = cfgpath + xmlfilename + ".xml";
		strXML = this.codeToString(strXML);
		if (!this.isFileExists(filePath)) {
			File f = new File(filePath);
		}
		PrintWriter pw = null;
		try {
			pw = new PrintWriter(new FileOutputStream(filePath));
			pw.write(strXML);
			pw.flush();
			pw.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void SaveStringAsXml(String xmlfilename, String strXML) {
		String filePath = cfgpath + xmlfilename + ".xml";
		//C:/Program%20Files/Apache%20Software%20Foundation/Tomcat%206.0/webapps/CoreFS/WEB-INF/cfgfiles/
		//strXML = this.codeToString(strXML);
		filePath=filePath.substring(1);
		filePath=filePath.replace("%20", " ");
		File f = new File(filePath);
		if (!f.exists()) {
		  try {
			f.createNewFile();
		} catch (IOException e) {
			e.printStackTrace();
		}
		}

		PrintWriter pw;
		try {
//			pw = new org.dom4j.io.XMLWriter( 
//			        new FileOutputStream(filePath));
			try {
				pw = new PrintWriter(filePath,"utf-8");
				pw.write(strXML);
				pw.flush();
				pw.close();
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	}
}
