package es.aeat.eett.misc;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Pattern;

import javax.swing.tree.DefaultMutableTreeNode;

import org.apache.log4j.Logger;
import org.jdom.Attribute;
import org.jdom.Element;
import org.jdom.Document;
import org.jdom.JDOMException;
import org.jdom.filter.ElementFilter;
import org.jdom.input.SAXBuilder;


public class StatisticsIndexBuilder {
	//private Logger l=org.apache.log4j.Logger.getRootLogger().error(message);
	private static final Logger LOGGER=Logger.getLogger(StatisticsIndexBuilder.class);
	//public static  String PATH_JRUBIKWEB="/Archivos de programa/Apache Software Foundation/Tomcat 5.5/webapps/JRubikWebDev";
	//public static final String PATH_JRUBIKWEB_QUERIES=PATH_JRUBIKWEB+"/WEB-INF/queries";
	public static final String PATH_JRUBIKWEB_QUERIES = "/WEB-INF/queries";
	
	private static final  String FILE_INDEX_NAME="indice_xml.jsp";
	private static final String TAG_UL_INIT="<ul>\n";
	private static final String TAG_UL_END="</ul>\n";
	private static final String TAG_LI_INIT="<li>";
	private static final String TAG_LI_END="</li>\n";

	private static final String TAG_A_INIT="<a";
	private static final String TAG_A_END="</a>";

	private String path;
	private String locale;
	private File fBase;
	private String hostName;
	
	private StatisticsIndexBuilder(String hostName, String path, String locale) {
		this.hostName=hostName;
		this.path=path;
		this.locale=locale;		
	}

	public static String build(String hostName, String path, String locale){
		return new StatisticsIndexBuilder(hostName, path,locale).build();
		
	}
	private File getFolderQueries(){
		if(path!=null){
			File f=new File(path);			
			return new File(f, PATH_JRUBIKWEB_QUERIES);
		}
		return null;
	}
	private String build() {
		fBase=getFolderQueries();
		if(fBase!=null){
			LOGGER.info("pathBase: "+path);
			LOGGER.info("File: "+fBase.getAbsolutePath());
			return getIndex(fBase, fBase);
		}
		return null;
	}
	private String getIndex(File f, File fBase){
		DefaultMutableTreeNode node=new DefaultMutableTreeNode(fBase);
		populateTree(f, fBase, node);
		purgeTree(node);
		StringBuilder sb=new StringBuilder();
//		sb.append("<html>\n");
//		sb.append("\t<body>\n");
				
		populateStringDocument(node, sb);
		
//		sb.append("\t</body>\n");
//		sb.append("</html>\n");
		
		
		return sb.toString();
	}
	
	private void populateStringDocument(DefaultMutableTreeNode node,
			StringBuilder sb) {

		
		int nChild=node.getChildCount();
		String sIdent="";
		for (int ident = -1; ident < node.getLevel(); ident++){
			sIdent +="\t";
		}						
		
		if(nChild>0 && !node.isRoot()){
			sb.append(sIdent);
			
			sb.append(TAG_LI_INIT);
			File f=(File) node.getUserObject();
			if(f!=null){								
				String name=getName(f,fBase);
				String[] rs=name.split("/");
				name=rs[rs.length-1];
				
				sb.append(name);
			}
			sb.append("\n");
			sb.append(sIdent);
			sb.append(TAG_UL_INIT);
		}		
		boolean hayElemento=false;
		if(node.isLeaf()){
			File f=(File) node.getUserObject();
			if(f!=null && !f.equals(fBase)){
				sb.append(sIdent);
				sb.append(TAG_LI_INIT);
				////////////////////////////////
				//<li><a href="url...">Reineta</a></li>
				sb.append(TAG_A_INIT);
				sb.append(" href=\"");
				sb.append(getUrl(node));
				sb.append("\">");
				//sb.append(TAG_A_END);
				String name=getName(f,fBase);
				String[] rs=name.split("/");
				name=rs[rs.length-1];
				
				sb.append(name);
				sb.append(TAG_A_END);
				///////////// TAG_A_INIT
//				String name=getName(f,fBase);
//				String[] rs=name.split("/");
//				name=rs[rs.length-1];
//				
//				sb.append(name);
				
				hayElemento=true;
			}
		}
		for (int i = 0; i < nChild; i++) {
			populateStringDocument((DefaultMutableTreeNode) node.getChildAt(i),sb);
		}
		
		if(hayElemento){
			if(nChild>0){
				sb.append("\n");
				sb.append(sIdent);
			}
			sb.append(TAG_LI_END);
		}
		if(nChild>0  && !node.isRoot()){
			sb.append(sIdent);
			sb.append(TAG_UL_END);
			
			sb.append(sIdent);
			sb.append(TAG_LI_END);
		}
	}

	private void populateTree(File f, File fBase, DefaultMutableTreeNode node){
		if(!"CVS".equalsIgnoreCase(f.getName())){
			File[] files=f.listFiles();
			for (int i = 0; files!=null && i < files.length; i++) {
				if(!"CVS".equalsIgnoreCase(files[i].getName())){
					if(files[i].isDirectory()){
						DefaultMutableTreeNode nChild=new DefaultMutableTreeNode(files[i]);
						node.add(nChild);
						populateTree(files[i], fBase, nChild);
					}if( FILE_INDEX_NAME.equalsIgnoreCase(f.getName())){
						//String name=getName(files[i],fBase);
						DefaultMutableTreeNode nChild=new DefaultMutableTreeNode(f);
						node.add(nChild);
					}
				}
			}
		}
	}
	@SuppressWarnings("unchecked")
	private void purgeTree(DefaultMutableTreeNode node) {
		List<DefaultMutableTreeNode> list=new ArrayList<DefaultMutableTreeNode>();
		
		Enumeration<DefaultMutableTreeNode> e=node.preorderEnumeration();
		while(e.hasMoreElements()){
			DefaultMutableTreeNode n= e.nextElement();
			if(n.isLeaf() && !n.equals(node.getRoot())){
				File f=(File) n.getUserObject();
				if(f.isDirectory()){
					File[] files=f.listFiles();
					boolean containsIndex=false;
					for (int i = 0; files!=null && i < files.length; i++) {
						if(FILE_INDEX_NAME.equalsIgnoreCase(files[i].getName())){
							containsIndex=true;
							break;
						}
					}
					if(!containsIndex){
						list.add(n);
					}
				}
			}
		}
		boolean result=!list.isEmpty();
		for (DefaultMutableTreeNode n : list) {
			DefaultMutableTreeNode nParent= (DefaultMutableTreeNode) n.getParent();
			if(nParent!=null){
				nParent.remove(n);
			}
		}
		if(result){
			purgeTree(node);
		}
	}

	private String getName(File f, File fBase){
		String result=f.getAbsolutePath();
		String base=fBase.getAbsolutePath();
		if(result.length()>base.length()){
			result=result.substring(base.length());
			if(result.length()>1 && result.startsWith("\\")){
					result=result.substring(1);					
			}
			//System.out.println(result);
			if(result.length()< result.length() - FILE_INDEX_NAME.length() - 1){
				result=result.substring(0,result.length() - FILE_INDEX_NAME.length() - 1);
				//LOGGER.info("Cambio name3: "+result);
			}
			result = result.replace('\\', '/');
		}
//		HttpServletRequest r;
//		r.getParameterMap();
		
		return result;
	}
	private Object getUrl(DefaultMutableTreeNode node) {
		//http://localhost:8080/JRubikWebDev/home.jsp?estad=primas/2007
		//http://localhost:8080/JRubikWebDev/home.jsp?estad=foodmart	
		StringBuilder sb=new StringBuilder();
		File f=(File) node.getUserObject();
		//sb.append("http://localhost:8080/");
		sb.append("http://");
		String server=(hostName!=null)?hostName:"localhost";
		sb.append(server);
		sb.append(":8080/");
		String p=path.replace('\\', '/');
		
		String[] paths=p.split("/");
		String appName=paths[paths.length-1];
		sb.append(appName);
		sb.append("/home.jsp?estad=");
		String statName=getName(f,fBase);
		sb.append(statName);
		sb.append(getTema(f));
		sb.append(getLocale());
		
		return sb.toString();
	}
	private final Pattern patternFmt = Pattern.compile("\\<fmt.*?\\>",Pattern.MULTILINE);
	//titulolargo=": <c:out value='${index_menu_titulo}'/>"
	private final Pattern patternOut = Pattern.compile("\\<c:out.*/\\>",Pattern.MULTILINE);
	private Object getTema(File f) {
		String tema="&tema=";
		String result="";
		//return "&tema=irpf";
		StringBuilder sb=JspReader.read(new File(f, FILE_INDEX_NAME));
		sb=new StringBuilder(patternFmt.matcher(sb).replaceAll(""));
		sb=new StringBuilder(patternOut.matcher(sb).replaceAll(""));
		
		//System.out.println(sb.toString());
		if(sb.length()>0){
			try {
				Document document= JDomReader.read(sb);
				
				Iterator<?> it= document.getDescendants(new ElementFilter("estadistica"));					
				Element eEstat=null;
				if(it.hasNext()){
					eEstat=(Element) it.next();
				}
				if(eEstat!=null){
					Attribute aTema=eEstat.getAttribute("tema");
					if(aTema!=null){
						result=tema+aTema.getValue();
						//System.out.println("Ok: "+f.getAbsolutePath());
					}
				}
			} catch (Exception e) {
//				//System.out.println("Error: "+f.getAbsolutePath());
//				System.out.println("\n\n---------------");
//				System.out.println(sb.toString());
//				e.printStackTrace();
//				System.out.println();
				//System.exit(0);
			}
		}
		if(result.length()==0){
			//Se intenta con el nombre de la estadistica
			String name=getName(f,fBase);
			String[] rs=name.split("/");
			if(rs.length>0){
				result=tema+rs[0];
			}
		}
		return result;
	}

	private Object getLocale() {
		if(locale!=null){
			return "&lang="+locale;
		}
		return "&lang=es";
	}

	public static void main(String[] args) {
		String ruta="/Archivos de programa/Apache Software Foundation/Tomcat 5.5/webapps/JRubikWeb_V1_1";
		String result=StatisticsIndexBuilder.build(null, ruta, null);
		System.out.println(result);
	}

}
abstract class JDomReader {
	static Document read (StringBuilder sb) throws Exception {
	
	    SAXBuilder builder = new SAXBuilder();
	    try {
	    	InputStream is=new BufferedInputStream(new ByteArrayInputStream(sb.toString().getBytes()));
	        Document doc = builder.build(is);
	        return doc;  //Fichero valido
	    }
	    catch (JDOMException e) {  //  fichero NO valido.
	    	//e.printStackTrace();
	        throw new Exception("buffer is no valid.",e );
	    }
	}
}

abstract class JspReader {
	private static final Logger LOGGER=Logger.getLogger(JspReader.class);
		
	static StringBuilder read(File f){
		BufferedReader reader=null;
		StringBuilder sb=new StringBuilder();
		try {
			sb.append("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>"+"\n");
			reader = new BufferedReader(new FileReader(f)); 	 
			String line;
			boolean removing=false;
			boolean afterEsta=false;
			String TAG_EST="<estadistica";
			while ((line = reader.readLine()) != null) {
				if(!afterEsta){
					int pos=line.toLowerCase().indexOf(TAG_EST);
					if(pos>-1){
						afterEsta=true;
						String sIn=line.substring(0, pos+TAG_EST.length());
						String sEnd=line.substring(pos+TAG_EST.length());
						line=sIn +" xmlns:c=\"http://java.sun.com/jstl/choss\" "+sEnd;
					}else{
						continue;
					}
				}
				line=line.trim();
				//No se copian las lineas que no seon XML
				if(line.length()>0 && !line.startsWith("<%@") && !line.startsWith("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>")){
					if(removing){
						int posEnd=line.indexOf("%>");
						if(posEnd>-1){
							line=line.substring(posEnd+2);
							removing=false;
						}
					}
					if(!removing){
						int posIni=line.indexOf("<%");
						if(posIni >-1){
							int posEnd=line.indexOf("%>");
							if(posEnd>-1){
								String end=line.substring(posEnd+2);
								//line=line.substring(posIni);
								line=line.substring(0, posIni)+end;
							}else{
								line=line.substring(posIni+2);
								removing=true;
							}
						}
					}
					if(!removing && line.length()>0){
						sb.append(line+"\n");
					}
				}
			}
			return sb;
		} catch (FileNotFoundException e) {
			LOGGER.error( e);
		} catch (IOException e) {
			LOGGER.error( e);
		}finally{
			try {
				if(reader!=null)
					reader.close();
			} catch (IOException e) {
			}				
		}
		return new StringBuilder();
	}
}

