module Main where
	
import Char
import Graphics.UI.WX	
import Graphics.UI.WXCORE
import Regexp
import HXML

import MyParserSpec
import Directory
import IO
import DeleteBlnFromXML
import Debugger
import Sim
import ShowFormXML
import Defs

home::String
home = "C:\\Javi\\EU-INDIA\\VERDIHaskell"

guiVerdi=do{
	--Global variables
	   specification<-varCreate [];
	   web<-varCreate [];
	   webnames<-varCreate [];
	   readablespec<-varCreate [];
	   errors<-varCreate[];
	   gseespec<-varCreate[];
	   readablehtml<-varCreate[];
	   htmlpage<-varCreate [];



	--Main Window
	   wverdi<-frame [text:="GVERDI 1.0"];
	   
	   pverdi<-panel wverdi [];
	   pfiles<-panel pverdi [];
	   perrors<-panel pverdi [];
           
	   --Elements
	   sp<-entry pfiles [];
	   wsite<-entry pfiles [];
	   errtext<-textCtrl perrors  [wrap := WrapNone];
	   title<-staticText pverdi [text:="GVERDI", fontSize:=14];
	   subtitle<-staticText pverdi [text:="VErification and Rewriting for Debugging Internet sites ",fontSize:=8, color:=grey];
	   labsp<-staticText pfiles [text:="Specification filename "];
	   labw<-staticText pfiles [text:="Web site directory "];
	   check<-button pfiles [text:="CHECK!",color:=red];
	   clear<-button pfiles [text:="Clear"];
	   quit<-button pfiles [text:="Quit"];
	   help<-button pfiles [text:="Help"];
	   about<-button pfiles [text:="About"];
	   showspec<-button pfiles [text:="Show Specs"];
	   showWeb<-button pfiles [text:="Show Web"];
	   fileb<-smallButton pfiles [text:="..."];		   
	   dirb<-smallButton pfiles [text:="..."];
	   files<-button pfiles [text:="Load!",enabled := False];		   
	   dirs<-button pfiles [text:="Load!",enabled := False];


	   --Layout
	   set wverdi [layout := container pverdi (margin 5 $ fill $
				     column 5 [ hfill $ row 3 [widget title,column 5 [vspace 4,widget subtitle]],
						container pfiles $ 
						hfill $(column 5 [
							hfill $ boxed "Input Files" $ grid 5 5 [[widget labsp,hfill $ widget sp,widget fileb,widget files],
					       			   	  [widget labw,hfill $ widget wsite,widget dirb,widget dirs]],
							 row 5 [hfill $ widget check, widget showspec, widget showWeb, widget clear, widget quit,widget help, widget about]
							]),
						container perrors $
						 (fill $ boxed "Errors Found"  $ fill $ widget errtext)
						])
			];
	   
						
	   windowSetClientSize wverdi (sz 650 500); 

	--Help Window
	   whelp<-frameFixed[text:="Help", visible:=False];	
	   phelp<-panel whelp [];
	   
	   --Elements
	   helptext<-staticText phelp [text:="     ************************************************************************\n\
                                          \                                     How to use GVERDI\n\
					   \     ************************************************************************\n\n\
					\    1. Load a Web Specification File containig the set of rules to check\n\
					\    2. Load the Web Site to check (giving as input the main directory name)\n\
					\    3. Check errors!"];
	   bclosehelp<-button phelp [text := "OK"];

	   --Layout
	   set whelp [layout := container phelp ( 
					column 5 [hfill $ widget helptext, alignCenter $ widget bclosehelp, vspace 5 ]
				)
			];

	   windowSetClientSize whelp (sz 360 130);
	  



	   -- Show Specification Window


	   wshowspec<-frame [text:="Web Specifications", visible:=False];

	   pseespec<-panel wshowspec [];
	   pss<-panel pseespec [];

	   -- Elements
	   spectext<-textCtrl  pss [wrap := WrapLine];  --[wrap := WrapNone];


	   bclosespecs<-button pseespec  [text := "OK"];


	   --Layout


	   set wshowspec [layout := container pseespec (margin 5 $ fill $
					column 5 [ 
						 container pss $
						 (fill $ boxed "Specification File"  $ fill $ widget spectext), hfill $ widget bclosespecs ]

						 
				)
			];


	   windowSetClientSize wshowspec (sz 640 480);



	  -- Show Web Window


	   wshowWeb<-frame[text:="XML", visible:=False];

	   pseeXML<-panel wshowWeb [];
	   pxml<-panel pseeXML [];
	   ploadWeb<-panel pseeXML [];

	   -- Elements


	   xmltext<-textCtrl pxml [wrap := WrapLine];
	   labhtml<-staticText ploadWeb [text:="Web page name "];
	   showterm<-button pseeXML [text:="Show Term"];
	   showxml<-button pseeXML [text:="Show XML"];
	   bcloseWeb<-button pseeXML [text := "Close"];
	   selectfiles<-singleListBox ploadWeb [text := ""];


	   --Layout

	   set wshowWeb [layout := container pseeXML (margin 5 $ fill $
				       column 5 [
						container ploadWeb $ 
						(hfill $ boxed "Web page" $ margin 5 $ row 5 [widget labhtml, hfill $ widget selectfiles ]),
						container pxml $
						(fill $ boxed "Show Web" $ fill $ widget xmltext), 
						row 5 [hfill $ widget bcloseWeb,  hfill $ widget showterm, hfill $ widget showxml]]
				)
			];


	   windowSetClientSize wshowWeb (sz 640 480);


	   
		
	--Actions
	   set clear [on command := set errtext [text:=""]];
	   set bclosehelp [on command := set whelp [visible:=False]];
	   set help [on command := set whelp [visible:=True]];
	   set bclosespecs [on command := set wshowspec [visible:=False]];
	   set showspec [on command := do{
					  set wshowspec [visible:=True];
					  file2<-varGet readablespec;
					  set spectext [text:= showhead file2 ]
						}];
	   set bcloseWeb [on command := set wshowWeb [visible:=False]];
	   set showWeb [on command := do{
					  set wshowWeb [visible:=True];

					   sel<-varGet webnames;
					   itemsDelete selectfiles;
					   set xmltext [text:=""];

					    
					   showitemappend selectfiles sel;


						}];

	   set selectfiles [on  select := do {
						sel<-varGet webnames;
						dir<-get wsite text;
						dir2<-get selectfiles selection;
						dir3<-get selectfiles (item dir2);
						varSet htmlpage (dir++"\\"++dir3);

						set showterm [enabled:=True];
						set showxml [enabled:=True]

								}]; 


	   set showterm  [on command := do {
						set wshowWeb [visible:=True];
						file<-varGet htmlpage;
						content2<-w2T file;
					
						set xmltext [text:=  show content2]
								}];

	   set showxml  [on command := do {
						set wshowWeb [visible:=True];
						file<-varGet htmlpage;  
						content<-readFile file;
						varSet readablehtml content;
						html2<-varGet readablehtml;
						
						set xmltext [text:= (showFormattedXML'.parseXML.deleteBlnFromXML) html2]

								}];

	   set about [on command := 
            infoDialog wverdi "About GVERDI" "        GVerdi 1.0 (March 2005) \n\n\ 
            \by Javier García-Vivó\n\n\
            \contact: jgarciavivo@dsic.upv.es"];    
	   set quit [on command:=do {close wverdi; close whelp; close wshowspec; close wshowWeb; {-close wseeterm-}}];

	   set fileb [on command:= do { 
					specf<-fileOpenDialog wverdi False True "Specification File" [("Any file (*.*)",["*.*"])] "" "";
					case specf of
						Nothing->do{set sp [text:=""]}
						Just filename->do {set sp [text:=filename];
								   set files [enabled:=True];}
					}];
 	   set dirb [on command:= do {  
					webdir<-dirOpenDialog wverdi True "Wb Site Directory" "";
					case webdir of
						Nothing->do{set wsite [text:=""]}
						Just dirname->do {set wsite [text:=dirname];
								  set dirs [enabled:=True]}
					}];
	   set files [on command := do{file<-get sp text;
					loadSpec specification readablespec file;
					 }];
	   set dirs  [on command := do {
					dir<-get wsite text;
					webnamesaux<-loadWeb dir;
					webaux<-web2Tree webnamesaux;
					setCurrentDirectory home;
					varSet webnames webnamesaux;
					varSet web webaux;
					--putStrLn "WEBSITE";
					--print (toNoAttsList webaux);
					putStrLn "Web Site loaded!"}];

	   


	   set check [on command := do{ 
					spec<-varGet specification;
					website<-varGet web;
					
					
					webfilenames<-varGet webnames;
					
					errors<-debug website spec webfilenames;
					finalerr<-return (concat(noRepeat errors));
					nerrors<-return(length finalerr);
					set errtext [text:=(concat(finalerr))++"\n"++(show nerrors)++" Errors found",color:=blue,fontSize:=14]
					}]

	}

--              --
--   Functions  --
--              --
 
noRepeat [] = []
noRepeat (x:xs) = if (elem x xs)
		  then (noRepeat xs)
		  else (x:(noRepeat xs))


deleteBln _ [] = []
deleteBln mutex (x:xs)
	|(x<=' ') && (mutex==0) = deleteBln 0 xs
	|(x==''') && (mutex==0) = x:(deleteBln 1 xs)
	|(x==''') && (mutex==1) = x:(deleteBln 0 xs)
	|(x<=' ') && (mutex==0) = deleteBln 0 xs
	|(x=='&') && (mutex==0) = x:(deleteBln 1 xs)
	|(x=='&') && (mutex==1) = x:(deleteBln 0 xs)
	|otherwise = x:(deleteBln mutex xs)


showhead [] = []				
showhead x = (show (head(x)))++"\n"++(showhead (tail(x)))


showitemappend w [] = itemAppend w [] 
showitemappend w x = 	do{

			itemAppend w (head(x));
			showitemappend w (tail (x)) 
					}



--   ParseSpec                              --
--parseSpec:: [String]->[(Tree XMLNode,Tree XMLNode)]

parseSpec [] = []
parseSpec listSpec = map specPairs (map (tokenList.(deleteBln 0)) listSpec)



--   LoadSpec  --

loadSpec spec readspec file = do 
	           {
                    content<-readFile file;
	            ret<-return (parseSpec (lines content));
		    varSet readspec (lines content);
	            varSet spec ret;
		    --putStrLn "SPECIFICATION:";
		    --print ret;
	     	    putStrLn "Web specification loaded! "}

w2T [] = do {return []}
w2T file = do {content<-readFile file;
		return ([(formatTree.parseXML.deleteBlnFromXML) content])}
    	
--   LoadWeb   --


loadWeb dir = do
 		  {
		   contents<-getDirectoryContents dir;
		   setCurrentDirectory dir;
		   filtcontents<-return (filterweb contents);
		   return filtcontents}
		    	where
				filterweb [] = []
				filterweb (x:xs)
					|(length x)>5 && (reverse (take 5 (reverse x))==".html") = x:(filterweb xs)
					|otherwise = filterweb xs
			


web2Tree [] = do {return []}					        
web2Tree (w:ws) = do{ y<-w2Tree w;
		      ys<-web2Tree ws;
		      return (y++ys)}
			where 
				w2Tree [] = do {return []}
				w2Tree w = do
					{content<-readFile w;
					 return ([(formatTree.toNoAtts.parseXML.deleteBlnFromXML) content])}   					

toNoAttsList [] = []
toNoAttsList (s:s1) = toNoAtts s : toNoAttsList (s1)


toNoAtts y  = case y of
		Tree RTNode n -> Tree RTNode (map toNoAtts n)
		Tree (TXNode x) [] -> Tree (TXNode x) []
		Tree (ELNode x []) n -> Tree (ELNode x []) (map toNoAtts n)
		Tree (ELNode x m)  n -> Tree (ELNode x []) ((attToGI m) ++ (map toNoAtts n))
		Tree (PINode x []) n -> Tree (TXNode "artificial" ) []  
		Tree (PINode x z) n -> Tree (TXNode "artificial" ) []
		Tree (CXNode x) n -> Tree (TXNode "artificial") []
		Tree (ENNode x) n -> Tree (TXNode "artificial") []


attToGI [] = []
attToGI ((att, val):ms) =( (Tree (ELNode att []) [Tree (TXNode val) []]) : (attToGI ms))






main = start guiVerdi


