package eu.dnetlib.client;

import java.util.ArrayList;

import com.github.gwtbootstrap.client.ui.Heading;
import com.google.gwt.event.dom.client.LoadEvent;
import com.google.gwt.event.dom.client.LoadHandler;
import com.google.gwt.http.client.URL;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Frame;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.RootPanel;

import eu.dnetlib.client.rightColumn.DataBox;
import eu.dnetlib.client.rightColumn.PreviewBox;
import eu.dnetlib.shared.ValuesOfFields;

public class Generate {

	private static Generate instance = new Generate();
	private Frame theme1 = new Frame();
	private Frame themeForTable = new Frame();
	private FlowPanel loader_big = new FlowPanel();
	private FlowPanel whiteFilm = new FlowPanel();
	
	private FlowPanel loader_big_table = new FlowPanel();
	private FlowPanel whiteFilm_table = new FlowPanel();
	
	private String basic_URL = new String("http://vaggelas.athenarc.gr/stats/");
	
	private Heading infoHeading = new Heading(3);
	private Heading infoHeading_table = new Heading(3);
	private Timer timer;
	private HTML loadingWheel = new HTML("<div class=\"loader-big\"></div><div class=\"whiteFilm\"></div>"); 
	

	public String getBasic_URL() {
		return basic_URL;
	}


	private Generate(){
		theme1.addLoadHandler(new LoadHandler() {
			
			@Override
			public void onLoad(LoadEvent event) {
				
				RootPanel.get("highchart").removeStyleName("loading");
				RootPanel.get("highchart").remove(loader_big);
				RootPanel.get("highchart").remove(whiteFilm);
				timer.cancel();
				infoHeading.setText("");
			}
		});
		
		themeForTable.addLoadHandler(new LoadHandler() {
			
			@Override
			public void onLoad(LoadEvent event) {
				// TODO Auto-generated method stub

				RootPanel.get("tableChart").removeStyleName("loading");
				RootPanel.get("tableChart").remove(loader_big_table);
				RootPanel.get("tableChart").remove(whiteFilm_table);
				timer.cancel();
				infoHeading_table.setText("");
			}
		});
	}
	
	public static Generate getInstance() {
		return instance;
	}
	
	public Frame getThemeForTable(){
		return this.themeForTable;
	}

	public Frame getTheme1() {
		return this.theme1;
	}


	public void setTheme1(Frame theme1) {
		this.theme1 = theme1;
	}

		public String generateURLs(final ValuesOfFields fieldsValues ,int WhoToReturn){
		
			loader_big.setStyleName("loader-big");
			whiteFilm.setStyleName("whiteFilm");
			loader_big_table.setStyleName("loader-big");
			whiteFilm_table.setStyleName("whiteFilm");
			loader_big.add(infoHeading);
			loader_big_table.add(infoHeading_table);
			infoHeading_table.addStyleName("info-preview");
			infoHeading_table.setText("");
			infoHeading.addStyleName("info-preview");
			infoHeading.setText("");
			
			
			String URL_theme1=basic_URL+"merge.php?com=query&data=[";
			String URL_theme2;
			String URL_theme3;
			ArrayList<Integer> whoToEnable = new ArrayList<Integer>();
			for(int y=0;y<ValuesOfFields.getInstance().getColumnsDataList().size();y++){
				if(fieldsValues.getColumnsDataList().get(y).isEnabled()){
					whoToEnable.add(y);
				}
			}
			for(int y=0;y<whoToEnable.size();y++){
				//if(fieldsValues.getColumnsDataList().get(y).isEnabled()){
					if(fieldsValues!=null){
					
						URL_theme1=URL_theme1.concat("{\"table\":\""+fieldsValues.getColumnsDataList().get(whoToEnable.get(y)).getDataSource()+"\",");
						URL_theme1=URL_theme1.concat("\"fields\":[");
						URL_theme1=URL_theme1.concat("{\"fld\":\""+fieldsValues.getColumnsDataList().get(whoToEnable.get(y)).getY_values()+"\",\"agg\":\""+fieldsValues.getColumnsDataList().get(whoToEnable.get(y)).getTypeOf().replaceAll(" of", "")+"\",\"type\":\"column\",\"yaxis\":"+(1)+",\"c\":"+fieldsValues.isCumulative()+"}");
						
						
						URL_theme1=URL_theme1.concat("],");
						
						
						//font weights for title and subtitle
						String fontWeightStartTitle = new String();
						String fontWeightEndTitle = new String();
						if(fieldsValues.isFontBoldTitle()){
							fontWeightEndTitle = fontWeightEndTitle.concat("</b>");
						}
						if(fieldsValues.isFontItalicTitle()){
							fontWeightEndTitle = fontWeightEndTitle.concat("</i>");
						}
						if(fieldsValues.isFontItalicTitle()){
							fontWeightStartTitle = fontWeightStartTitle.concat("<i>");
						}
						if(fieldsValues.isFontBoldTitle()){
							fontWeightStartTitle = fontWeightStartTitle.concat("<b>");
						}
						
						String finalTitle = fontWeightStartTitle + fieldsValues.getTitle() + fontWeightEndTitle;
						
						String fontWeightStartSubTitle = new String();
						String fontWeightEndSubTitle = new String();
						if(fieldsValues.isFontBoldSubtitle()){
							
							fontWeightEndSubTitle = fontWeightEndSubTitle.concat("</b>");
						}
						if(fieldsValues.isFontItalicSubtitle()){
							
							fontWeightEndSubTitle = fontWeightEndSubTitle.concat("</i>");
						}
						if(fieldsValues.isFontItalicSubtitle()){
							fontWeightStartSubTitle = fontWeightStartSubTitle.concat("<i>");
						}
						if(fieldsValues.isFontBoldSubtitle()){
							fontWeightStartSubTitle = fontWeightStartSubTitle.concat("<b>");
						}
						String finalSubTitle = fontWeightStartSubTitle + fieldsValues.getSubtitle() + fontWeightEndSubTitle;
						
						URL_theme1=URL_theme1.concat("\"xaxis\":{\"name\":\""+fieldsValues.getColumnsDataList().get(whoToEnable.get(y)).getX_values()+"\",\"agg\":\""+fieldsValues.getColumnsDataList().get(whoToEnable.get(y)).getTypeOf().replaceAll(" of", "")+"\"},");
						URL_theme1=URL_theme1.concat("\"group\":\""+fieldsValues.getColumnsDataList().get(whoToEnable.get(y)).getSplitBy()+"\",\"color\":\"\",\"type\":\"chart\",\"size\":"+fieldsValues.getNumberOfResults()+",\"sort\":\"xaxis\",\"xStyle\":{\"r\":"+fieldsValues.getRotation()+",\"s\":\""+fieldsValues.getUseSteps()+"\",\"l\":\"-\",\"ft\":\"-\",\"wt\":\"-\"},");
						URL_theme1=URL_theme1.concat("\"title\":\""+finalTitle+"\",\"subtitle\":\""+finalSubTitle +"\",\"xaxistitle\":\""+fieldsValues.getColumnsDataList().get(whoToEnable.get(y)).getDataserieNaming()+"\",\"yaxisheaders\":[\""+fieldsValues.getYaxis()+"\"],\"generalxaxis\":\""+fieldsValues.getXaxis()+"\",");
						
					}
				
					
					if(fieldsValues.getColumnsDataList().get(whoToEnable.get(y)).getFilters().size()==0){
						URL_theme1=URL_theme1.concat("\"theme\":"+0+",\"in\":[]");
					}else{
						URL_theme1=URL_theme1.concat("\"theme\":"+0+",\"in\":[],\"filters\":[");
						
						int counterOfEnabled = 0;
						for(int filtNum=0;filtNum<fieldsValues.getColumnsDataList().get(whoToEnable.get(y)).getFilters().size();filtNum++){
							if(fieldsValues.getColumnsDataList().get(whoToEnable.get(y)).getFilters().get(filtNum).isEnabled()){
								if(counterOfEnabled!=0){
									URL_theme1 = URL_theme1.concat(",");
								}
								counterOfEnabled++;
								int counter=0;
								URL_theme1=URL_theme1.concat("{\"name\":\""+fieldsValues.getColumnsDataList().get(whoToEnable.get(y)).getFilters().get(filtNum).getFieldValue()+"\",");
								if(fieldsValues.getColumnsDataList().get(whoToEnable.get(y)).getFilters().get(filtNum).getType().equals("Discrete")){
									URL_theme1 = URL_theme1.concat("\"values\":[");
									for(int discNum=0;discNum<fieldsValues.getColumnsDataList().get(whoToEnable.get(y)).getFilters().get(filtNum).getDiscreteValues().size();discNum++){
										if(counter>0){
											URL_theme1 = URL_theme1.concat(",");
										}
										URL_theme1 = URL_theme1.concat("\""+fieldsValues.getColumnsDataList().get(whoToEnable.get(y)).getFilters().get(filtNum).getDiscreteValues().get(discNum)+"\"");
										counter++;
									}
									
									URL_theme1 = URL_theme1.concat("],");
								}else if(fieldsValues.getColumnsDataList().get(whoToEnable.get(y)).getFilters().get(filtNum).getType().equals("Continuous")){
									URL_theme1 = URL_theme1.concat("\"max\":\""+fieldsValues.getColumnsDataList().get(whoToEnable.get(y)).getFilters().get(filtNum).getValueTo()+"\",\"min\":\""+fieldsValues.getColumnsDataList().get(whoToEnable.get(y)).getFilters().get(filtNum).getValueFrom()+"\",");
								}
								URL_theme1 = URL_theme1.concat("\"to\":\"-1\"}");
								
							}
						}
						URL_theme1=URL_theme1.concat("]");
					}
						
					
					if(y!=whoToEnable.size()-1){
						URL_theme1=URL_theme1.concat("},");
					}else{
						URL_theme1=URL_theme1.concat("}");
					}
		
			}
			
				URL_theme1=URL_theme1.concat("]");
			
			int option = fieldsValues.getOptionSelected();

			URL_theme1 = URL_theme1.concat("&info_types=[");
			boolean percent = false;
			boolean normal = false;
			boolean steps = false;
			boolean threeD = false;
			boolean donut = false;
			boolean none = false;
			boolean map = false;
			
			for(int i=0;i<whoToEnable.size();i++){
				URL_theme1 = URL_theme1.concat("\""+fieldsValues.getColumnsDataList().get(whoToEnable.get(i)).getTypeOfChart()+"\"");
				if(fieldsValues.getColumnsDataList().get(whoToEnable.get(i)).getTypeOfChart().equals("map")){
					map=true;
				}
				if(i!=whoToEnable.size()-1){
					URL_theme1 = URL_theme1.concat(",");
				}else{
					URL_theme1 = URL_theme1.concat("]");
				}
				if(ValuesOfFields.getInstance().getColumnsDataList().get(whoToEnable.get(i)).getStacking().equals("donut")){
					donut=true;
				}else if(ValuesOfFields.getInstance().getColumnsDataList().get(whoToEnable.get(i)).getStacking().equals("normal")){
					normal=true;
				}else if(ValuesOfFields.getInstance().getColumnsDataList().get(whoToEnable.get(i)).getStacking().equals("percent")){
					percent = true;
				}else if(ValuesOfFields.getInstance().getColumnsDataList().get(whoToEnable.get(i)).getStacking().equals("steps")){
					steps = true;
				}else if(ValuesOfFields.getInstance().getColumnsDataList().get(whoToEnable.get(i)).getStacking().equals("3D")){
					threeD=true;
				}else if(ValuesOfFields.getInstance().getColumnsDataList().get(whoToEnable.get(i)).getStacking().equals("none")){
					none=true;
				}
			}
		
			if(percent){
				URL_theme1 = URL_theme1.concat("&stacking=percent");
			}else if(normal){
				URL_theme1 = URL_theme1.concat("&stacking=normal");
			}else if(donut){
				URL_theme1 = URL_theme1.concat("&stacking=donut");
			}else if(none){
				URL_theme1 = URL_theme1.concat("&stacking=");
			}
			if(map){
				URL_theme1 = URL_theme1.replace("merge.php", "googleMaps.php");
			}
			percent = false;
			normal = false;
			steps = false;
			threeD = false;
			donut = false;
			
			if(steps){
				URL_theme1 = URL_theme1.concat("&steps=true");
			}else{
				URL_theme1 = URL_theme1.concat("&steps=false");
			}
				URL_theme1 = URL_theme1.concat("&fontFamily="+fieldsValues.getFontFamily());
				URL_theme1 = URL_theme1.concat("&spacing=["+fieldsValues.getSpacingTop()+","+fieldsValues.getSpacingRight()+","+fieldsValues.getSpacingBottom()+","+fieldsValues.getSpacingLeft()+"]");
				URL_theme1 = URL_theme1.concat("&style=[{\"color\":\""+fieldsValues.getColorTitle()+"\",\"size\":\""+fieldsValues.getSizeTitle()+"\"},{\"color\":\""+fieldsValues.getColorSubtitle()+"\",\"size\":\""+fieldsValues.getSizeSubtitle()+"\"},{\"color\":\""+fieldsValues.getColorXaxis()+"\",\"size\":\""+fieldsValues.getSizeXaxis()+"\"},{\"color\":\""+fieldsValues.getColorYaxis()+"\",\"size\":\""+fieldsValues.getSizeYaxis()+"\"}]");
				if(fieldsValues.getChartBackgroundColor().equals("")){
					URL_theme1 = URL_theme1.concat("&backgroundColor=rgba(255,255,255,1)");
				}else{
					URL_theme1 = URL_theme1.concat("&backgroundColor="+fieldsValues.getChartBackgroundColor()+"");
				}

				for(int colors=0;colors<10;colors++){
					URL_theme1 = URL_theme1.concat("&colors[]="+fieldsValues.getColors()[colors]);

				}
				
				URL_theme1 = URL_theme1.concat("&xlinew="+fieldsValues.getxLineWidth()+"&ylinew="+fieldsValues.getyLineWidth());
				URL_theme1 = URL_theme1.concat("&legends="+fieldsValues.isLegends());
				URL_theme1 = URL_theme1.concat("&tooltips="+fieldsValues.isTooltip());
						
				if(map){
					URL_theme1 = URL_theme1.concat("&region="+fieldsValues.getRegions());
					URL_theme1 = URL_theme1.concat("&dataMode="+fieldsValues.getDataMode());
					URL_theme1 = URL_theme1.replace("merge.php", "googleMaps.php");
				}
				
				
				
				URL_theme2=URL_theme1;
				URL_theme3=URL_theme1;
				
				
				RootPanel.get("highchart").addStyleName("loading");
				
				RootPanel.get("highchart").add(loader_big);
				RootPanel.get("highchart").add(whiteFilm);
				
				RootPanel.get("tableChart").addStyleName("loading");
				
				RootPanel.get("tableChart").add(whiteFilm_table);
				RootPanel.get("tableChart").add(loader_big_table);
				
				
                    timer = new Timer() {

                        @Override
                        public void run() {
                        	infoHeading.setText("We are processing your request, please wait..");
                        }
                    };
                    timer.schedule(10000);
                    

				this.getTheme1().setUrl(URL.encode(URL_theme1));
				if(!map){
					this.getThemeForTable().setUrl(URL.encode(URL_theme1.replace("merge.php", "infoForTable_new.php")));
				}else{
					this.getThemeForTable().setUrl(URL.encode(URL_theme1.replace("googleMaps.php", "infoForTable_new.php")));
					URL_theme1 = URL_theme1.replace("googleMaps.php", "merge.php");
				}
				
				//generateTableURLs(fieldsValues,URL_theme1);
			
				if(WhoToReturn==1){
					return URL_theme1;
				}else if(WhoToReturn==2){
					return URL_theme2;
				}else if(WhoToReturn==3){
					return URL_theme3;
				}else{
					return null;
				}
			
	}
		
		public String generateTableURLs(ValuesOfFields fieldsValues,String URL){
				
				new DataBox(URL.replace("merge.php", "infoForTable.php"));
			
				return URL;
			
	}
	
}
