package ITUannotation;

    
	import java.io.File;
	import java.io.IOException;
	import java.util.ArrayList;
	import java.util.Scanner;

	import javax.xml.parsers.DocumentBuilder;
	import javax.xml.parsers.DocumentBuilderFactory;
	import javax.xml.parsers.ParserConfigurationException;
	import javax.xml.xpath.XPath;
	import javax.xml.xpath.XPathExpressionException;
	import javax.xml.xpath.XPathFactory;
	import org.w3c.dom.Document;
	import org.w3c.dom.Element;
	import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

	public class Sentenceparser {
		private DocumentBuilder builder;
		private XPath path;
		private int wordcount;
		
		public Sentenceparser()
		 throws ParserConfigurationException
		 {
			DocumentBuilderFactory dbfactory= DocumentBuilderFactory.newInstance();
			builder = dbfactory.newDocumentBuilder();
			XPathFactory xpfactory = XPathFactory.newInstance();
			path = xpfactory.newXPath();
		 }	
		
		public int[] parsecheckbox(String s) {
			int[] arr = new int[3];
			int indexofslash = s.indexOf('/');
			int indexofStar = s.indexOf('*');

			String strilksayi = s.substring(0, indexofslash);
			int ilksayi = Integer.parseInt(strilksayi);
			String strikincisayi = s.substring(indexofslash + 1, indexofStar);
			int ikincisayi = Integer.parseInt(strikincisayi);

			String strcheckNum = s.substring(indexofStar + 1, s.length());
			int checkNum = Integer.parseInt(strcheckNum);
			arr[0] = ilksayi;
			arr[1] = ikincisayi;
			arr[2] = checkNum; 
			return arr;

		}
		
		/**
		 Parses an XML file containing an sentence list.
		 * @param fileName the name of the file
		 @return an array list containing all items in the XML file
		 */
		 public /*void*/ ArrayList<Syntactic_Elements> parse(File f)
		 throws SAXException, IOException, XPathExpressionException
		 {  			 
			 ArrayList<Syntactic_Elements> wordsofsent = new ArrayList<Syntactic_Elements>();
			 String fi=f.getName();
			 String[] filename=fi.split("\\.");
			 String ext=filename[filename.length-1];
			 if(ext.equals("xml")){
			    Document doc = builder.parse(f);
				Element docEle = doc.getDocumentElement();

				NodeList nl = docEle.getElementsByTagName("W");
				if(nl != null && nl.getLength() > 0) {
					for(int i = 0 ; i < nl.getLength();i++)
					{
						Element el = (Element)nl.item(i);

						Syntactic_Elements e = getSyntactic_Elements(el);

						wordsofsent.add(e);
					}
					
				}
			 }
			 else{// if(ext.equals("conll")){
				 ArrayList<String[]> sentence=new ArrayList<String[]>();
				 Scanner in=new Scanner(f,"UTF-8");
				 while(in.hasNext()){
					 String line=in.nextLine();
					 String[] columns=line.split("\t");					
					 sentence.add(columns);					 
				 }
				 ConllSentenceRelationFinder srf=new ConllSentenceRelationFinder(sentence);
				 ArrayList<ConllItem> crel=srf.getrelations();
				 int conlli=0;
				 int ig=1;
				 for(String[] columns:sentence){
					 Syntactic_Elements e;
					 conlli++;
					 
					 if(columns[1].equals("_")){
						 ig++;continue;
					 }
					 Relation r=null;
					 if(Integer.parseInt(columns[6])!=0){
						 r=new Relation(crel.get(Integer.parseInt(columns[6])-1).getwordnum(), crel.get(Integer.parseInt(columns[6])-1).getIgnum(), columns[7]);
					 }
					 else{
						 r=new Relation(0, 0, "");
					 }
					 e=new Syntactic_Elements(columns[1],ig,r);
					 ig=1;
					 wordsofsent.add(e);
				 }
				 wordcount=srf.getWordCount();
			 }
			 
				return wordsofsent;
		 }
	private Syntactic_Elements getSyntactic_Elements(Element el) {


			String content = el.getTextContent();


			String IG = el.getAttribute("IG");
			int ig= countig(IG);
			
			String rel = el.getAttribute("REL");
			Relation nwrltn=gettherelation(rel);
		
			Syntactic_Elements e = new Syntactic_Elements(content,ig,nwrltn);

			return e;
		}


	private String getTextValue(Element ele, String tagName) {
		// TODO Auto-generated method stub
		String textVal = null;
		NodeList nl = ele.getElementsByTagName(tagName);
		if(nl != null && nl.getLength() > 0) 
		{
			Element el = (Element)nl.item(0);
			textVal = el.getFirstChild().getNodeValue();
		}

		return textVal;
		
	}
//		 return items;
		 public int countwords(File f) throws SAXException, IOException, NumberFormatException, XPathExpressionException
		 {   String fi=f.getName();
		 	 String[] filename=fi.split("\\.");
		 	 String ext=filename[filename.length-1];
		 	 if(ext.equals("xml")){
		 
		 		 Document doc = builder.parse(f);
		 		 wordcount = Integer.parseInt(path.evaluate("count(/Set/S/W)",doc));
		 	 }
			 return wordcount;
			 
		 }
		 public int countig(String ig) //throws SAXException, IOException, XPathExpressionException
		 {
			 int cnum=0;
			 int indexoflastpharanthesis=ig.lastIndexOf('(');//ig deki son parantez aciliminin indexini aldim
			 //son parantezden 1 sonra gelen sayi checkbox numberi veriyor o yuzden +1 diyecegiz
			 cnum=Character.getNumericValue(ig.charAt(indexoflastpharanthesis+1));
			 return cnum;

		 }
		 public Relation gettherelation(String str)
		 {
			 int baglanansozcknum;
			 int cekimkumesinum;
			 String rel;
			 int indexofkoselip=str.indexOf('[');
			 int indexofilkcoma=str.indexOf(',');//get index of first virgul
			 int indexoflastcoma=str.lastIndexOf(',');
			 char afterk=str.charAt(indexofkoselip+1);
			 String ilksayi=str.substring(indexofkoselip+1,indexofilkcoma);
			 if(afterk==',')
			 {
				 rel="";
				 baglanansozcknum=0;
				 cekimkumesinum=0;
				 
			 }
			 else
			 {
				 baglanansozcknum=Integer.parseInt(ilksayi);
				 String ikincisayi=str.substring(indexofilkcoma+1,indexoflastcoma);
				 cekimkumesinum=Integer.parseInt(ikincisayi);
				 int indexacikprntz=str.indexOf('(');
				 int indexkapnprntz=str.indexOf(')');
				 rel=str.substring(indexacikprntz+1,indexkapnprntz);
				 //rel=
			 } 
			 Relation RLTN=new Relation(baglanansozcknum,cekimkumesinum,rel);
			 return RLTN;
		 }
	}



