package ITUannotation;

import java.util.ArrayList;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.lang.Object;
import java.util.ArrayList;
import java.util.regex.Pattern;

import javax.xml.bind.Marshaller;
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.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

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;



public class XMLCreator {
	private ArrayList<Words>wordsforXML;
	private String XmlStr;
	
	private DocumentBuilderFactory factory;
	private DocumentBuilder docBuilder;
	private Document doc;
	private File myFile;
	private TransformerFactory transfac;//= TransformerFactory.newInstance();
	private Transformer trans;// = transfac.newTransformer();
	private ArrayList<Syntactic_Elements> mysntItarr;
	private String xmlString,xmlStringPrint;
	private StreamResult result; 
	private  DOMSource source;

	/*for Morphological Analysis*/
	
	public XMLCreator(ArrayList<Words> wordsforXML) {
		this.wordsforXML=wordsforXML;
		init_XML();
		// TODO Auto-generated constructor stub
	}

	public String getXmlString() {
		for(int i=0;i<wordsforXML.size();i++)
		{
       	 	String wordstr=wordsforXML.get(i).getWordstr().replaceAll(" ", "");
			XmlStr=	XmlStr+"\n"+"<W IX=\""+Integer.toString(i+1)+"\" LEM=\"\" MORPH=\" \" IG='["+wordsforXML.get(i).getIG()+"]' REL=\"[,()]\"> "+wordsforXML.get(i).getWordstr()+" </W>";
		}
		// TODO Auto-generated method stub
		XmlStr=	XmlStr+"\n</S>\n</Set>";

		return XmlStr;
	}
	public void init_XML()
	{
		XmlStr="<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<Set sentences=\"1\">\n<S No=\"1\">";
	}
	
	///////////////////////////////////////////////////////////
	
	/*for Syntactic Analysis*/
	
	public XMLCreator(ArrayList<Syntactic_Elements> sntItarr, File opened) throws ParserConfigurationException, SAXException, IOException {
		
		mysntItarr=sntItarr;
		myFile=opened;
		
			createDocument();
			update();
			
			// TODO Auto-generated constructor stub
		}
		public XMLCreator() {
			myFile=null;
		// TODO Auto-generated constructor stub
			xmlString =xmlStringPrint="<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"
	        	+"\n<Set sentences=\"0\">"
	        	+"\n</Set>";
			
	}
		private void createDocument() throws ParserConfigurationException, SAXException, IOException {

			//Create instance of DocumentBuilderFactory
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		 
			//Get the DocumentBuilder
			DocumentBuilder docBuilder = factory.newDocumentBuilder();
		 
			//Parsing XML Document
			doc = docBuilder.parse(myFile);
		}
		void update()
		{
			Element docEle = doc.getDocumentElement();
			NodeList nl = docEle.getElementsByTagName("W");
			if(nl != null && nl.getLength() > 0) {
				for(int i = 0 ; i < nl.getLength();i++)
				{
					/*mysntItarr.get(i).getRLN().getBaglanilanSozcukNum()
					mysntItarr.get(i).getRLN().getCekimKumesiNum()
					mysntItarr.get(i).getRLN().getRelationStr()
					ile  setSyntactic_Elements(el) seklinde bir fonksiyon yazip bu isi hallet
					*
					*/

					//get the employee element
					Element el = (Element)nl.item(i);
					
					//get the Employee object
					setSyntactic_Elements(el,mysntItarr.get(i));

					//add it to list
		//			wordsofsent.add(e);//myEmpls.add(e);
				}
				
			}
		}
		private void setSyntactic_Elements(Element el, Syntactic_Elements Syntactic_Elements) {
			// TODO Auto-generated method stub
			
			String newrel="";
			if(Syntactic_Elements.getRLN().getDest()==0||Syntactic_Elements.getRLN().getRelationStr().contentEquals("Please select"))
			{
				newrel="[,( )]";
			}
			
			else
			{	
				String bagsozcknum=Integer.toString(Syntactic_Elements.getRLN().getDest());
				String cekimkumesinum=Integer.toString(Syntactic_Elements.getRLN().getPoint());
				String relStr=Syntactic_Elements.getRLN().getRelationStr();
				newrel="["+bagsozcknum+","+cekimkumesinum+",("+relStr+")]";
				//[18,1,(MODIFIER)]
			}
			el.setAttribute("REL", newrel);

			
		}
		
		public void ConverttoStr()
		{
			if (myFile!=null)
			{
			TransformerFactory transfac = TransformerFactory.newInstance();
		    try {
				
		    	//trans = transfac.newTransformer();
		    	transfac = TransformerFactory.newInstance();
		    	
		       trans = transfac.newTransformer();
		       trans.setOutputProperty(OutputKeys.INDENT, "yes");
		     //  trans.setOutputProperty(â€œ{http://xml.apache.org/xslt}indent-amountâ€�, â€œ4â€³);
		        //generating string from xml tree
		       
		      // Marshaller marshaller = jaxbContext.createMarshaller();
		       
		       XmlStr="<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<Set sentences=\"1\">\n<S No=\"1\">";
		       ArrayList <Node> nodeArr = new ArrayList<Node>();
		       
		       	for(int i = 0; i < doc.getElementsByTagName("W").getLength(); i++)	
		    	   nodeArr.add(doc.getElementsByTagName("W").item(i));
		       
		       	for(int i = 0; i < doc.getElementsByTagName("W").getLength(); i++)
		       	{
		       		String change = nodeArr.get(i).getAttributes().item(0).toString();
		       	 	int last = change.lastIndexOf("\"");
		       	 	change = change.substring(4, last);
		       	 	String wordstr=nodeArr.get(i).getTextContent().replaceAll(" ", "");
		       		XmlStr=	XmlStr+"\n"+"<W " +nodeArr.get(i).getAttributes().item(1)+ " " + nodeArr.get(i).getAttributes().item(2) +" " + nodeArr.get(i).getAttributes().item(3)+" IG='" +  change + "' " +nodeArr.get(i).getAttributes().item(4) +"> "+wordstr+" </W>";
		       	
		       	}	
		       	XmlStr=	XmlStr+"\n</S>\n</Set>";
		        System.out.println(XmlStr);
		        xmlStringPrint = xmlString = XmlStr;
		    /*    
		        StringWriter sw = new StringWriter();
		        result = new StreamResult(sw);
		        source = new DOMSource(doc);
		        trans.transform(source, result);
		        xmlString = result.getWriter().toString();//toString();
		        xmlStringPrint=xmlString.replaceAll("&quot;","\"" );
		   */     
		        //"\"", 
		//        xmlString=StringEscapeUtils.escapeJava(xmlString);"&quot;"
		        

		
			
		    } catch (TransformerConfigurationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (TransformerException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			}
		}
		public String sendxmlstring()
		{
			ConverttoStr();
			return xmlStringPrint;
		}
		public String sendoriginalxml()
		{
			ConverttoStr();
			return xmlString;
		}
		public DOMSource sendsource()
		{
			ConverttoStr();
			return source;
		}


	}
	
	
	

