package ibase.client;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import com.google.gwt.core.client.Callback;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.SplitLayoutPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
//import com.googlecode.gwtTableToExcel.client.TableToExcelClientBuilder;
import com.google.gwt.user.client.ui.Widget;

/**
 * 
 * The GraphComponent class create a FusionChart
 * 
 */
public class GraphComponent extends Composite
{
	/** The chartcontainer hold the FusionChart */

	private VerticalPanel mainContainer = new VerticalPanel();
	private SimplePanel gridContainer = new SimplePanel();
	private JSONObject jsonObjMetaData = new JSONObject();
	private JSONObject jsonObjData = new JSONObject();
	SplitLayoutPanel split = new SplitLayoutPanel();

	public static HashMap<String, HashMap> gridNGraphMeataDataMap = null;
	public final int STATUS_CODE_OK = 200;
	final LinkedHashMap<String, JSONObject> dataMap = new LinkedHashMap<String, JSONObject>();
	ArrayList<String> parameterList = null;
	ArrayList<String> idList = new ArrayList<String>();

	/**
	 * This constructor initializes the graph container
	 * 
	 */

	public GraphComponent(ArrayList<String> parameterList, JSONObject metaDataJsnObj)
	{
		this.jsonObjMetaData = metaDataJsnObj;
		this.parameterList = parameterList;
		mainContainer.setWidth("100%");
		mainContainer.add(new FilterCreator(parameterList, metaDataJsnObj));
		initWidget(mainContainer);
	}
	@SuppressWarnings("unchecked")
	public void buildChart(final LinkedHashMap<String, JSONObject> dataMap)
	{ 		
		JSONObject jsonObjFrGraph = null;
		String height = null;
		String width = null;
		String imageName = null;
		ArrayList graphDtlList = null;
		HashMap<String, ArrayList<String>> graphDataMap = null;
		HashMap<String, HashMap<String, String>> componentTypeMap = null;
		HashMap<String, HashMap<String, String>> datasourceMap = null;
		HashMap<String, String> componentMap = null;
		JSONObject graphJson = null;
		final String componentType = "componentType";
		String compType = "";
		String component ="";
		HashMap<String, ArrayList<String>> graphTypeMap = null;
		String dtSrouce="";
		if (idList.size() > 0)
		{
			for (int i = 0; i < idList.size(); i++)
			{
				RootPanel panel = RootPanel.get("chartContainer" + idList.get(i));
				panel.clear();
				if (panel.getElement().getFirstChild() != null)
				{
					panel.getElement().getFirstChild().removeFromParent();
				}
			}
			idList = new ArrayList<String>();
		}
		for (String componentId : gridNGraphMeataDataMap.keySet())
		{
			jsonObjFrGraph=new JSONObject();
			if(isNumeric(componentId))
			{
				idList.add(componentId);
				compType      = componentType.trim() +componentId.trim();
				graphDataMap  = gridNGraphMeataDataMap.get(componentId);
				datasourceMap = gridNGraphMeataDataMap.get("datasource"+componentId);
				dtSrouce      = ""+datasourceMap.get("datasource"+componentId); 
				
				//check code for datasource by Birendra Pandey
				
				graphTypeMap = gridNGraphMeataDataMap.get("type"+componentId);
				String type = ""+(graphTypeMap.get("type"+componentId));
				if("T".equalsIgnoreCase(type))
				{
					componentTypeMap = gridNGraphMeataDataMap.get(compType);
					component = "" + componentTypeMap.get("buildComponent"+componentId);
				}				
				jsonObjFrGraph = (JSONObject) dataMap.get(dtSrouce);
				if ("G".equalsIgnoreCase(type) &&  jsonObjFrGraph != null)
				{
					for (String graphNo : graphDataMap.keySet())
					{
						graphDtlList = graphDataMap.get(graphNo);
						imageName = (String) graphDtlList.get(0);
						width = (String) graphDtlList.get(1);
						height = (String) graphDtlList.get(2);
						graphJson = ChartCreator.buildChartData(graphDtlList, jsonObjFrGraph, dtSrouce);
						if (graphJson != null && graphJson.size() > 0)
						{
							this.createChart(graphJson.toString(), "chartContainer" + componentId, "chartContainer" + componentId, width, height, imageName);
						}
					}
				} 
				else if("T".equalsIgnoreCase(type) &&  jsonObjFrGraph != null)
				{
					RootPanel.get("chartContainer"+componentId).clear();
					//RootPanel.get().clear();
					ScrollPanel scrlPanel = new ScrollPanel();
					FlexTable flexTable   = new FlexTable();
					
					if ("FlexTable".equalsIgnoreCase(component))
					{
						CustomFlxTable customFlxTable = new CustomFlxTable();
						flexTable = customFlxTable.createFlxTbl(flexTable, gridNGraphMeataDataMap, jsonObjFrGraph,componentId);
						//This Block for Export to excel and PDF formate
						HorizontalPanel horizontalPnl = new HorizontalPanel();
						Button excelBtn = new Button("Export To Excel");
						excelBtn.setTitle("Excel");
						Button pdFBtn = new Button("Export To PDF");
						pdFBtn.setTitle("PDF");
						horizontalPnl.add(ibase.client.tabletoexcel.TableToExcelClientBuilder.fromTable(flexTable).withWidget(pdFBtn).buildExportFormWidget());
						horizontalPnl.add(ibase.client.tabletoexcel.TableToExcelClientBuilder.fromTable(flexTable).withWidget(excelBtn).buildExportFormWidget());
						//End Block for Export to excel and PDF formate
						scrlPanel.add(flexTable);
						scrlPanel.setStyleName("flextableScrlPnl");
						RootPanel.get("chartContainergrid").add(scrlPanel);
						RootPanel.get("chartContainer"+componentId).add(horizontalPnl);
				
					} else if("DataGrid".equalsIgnoreCase(component))
					{ 
						flexTable       = new FlexTable();
						CustomGrid data = new CustomGrid(10);
						flexTable       = data.jsonToArrayList(gridNGraphMeataDataMap, jsonObjFrGraph,dtSrouce,componentId);
						//This Block for Export to excel and PDF formate
						HorizontalPanel horizontalPnl = new HorizontalPanel();
						Button excelBtn = new Button("Export To Excel");
						excelBtn.setTitle("Excel");
						/*Button pdFBtn = new Button("Export To PDF");
						pdFBtn.setTitle("PDF");
						horizontalPnl.add(ibase.client.tabletoexcel.TableToExcelClientBuilder.fromTable(flexTable).withWidget(pdFBtn).buildExportFormWidget());*/
						//horizontalPnl.add(ibase.client.tabletoexcel.TableToExcelClientBuilder.fromTable(flexTable).withWidget(excelBtn).buildExportFormWidget());
						//End Block for Export to excel and PDF formate
						RootPanel.get("chartContainer"+componentId).add(flexTable);
						//RootPanel.get("chartContainer"+componentId).add(horizontalPnl);
					}				
				}
			}
		}
	}
    
	private native void createChart(String chartData, String containerId, String chartContainer, String width, String height, String imageName)
	/*-{
		try {
			$wnd.createFusionChart(chartData, containerId, chartContainer,width, height, imageName);
		} catch (e) {
			alert("Excpeiton :: GraphComponent : createChart [" + e.message		+ "]");
		}
	}-*/;
	@SuppressWarnings("unchecked")	
	public void getData(final Callback<JSONObject, String> callback, ArrayList<String> parameterList)
	{
		this.parameterList=parameterList;
		String viewOptionSelectd = parameterList.get(parameterList.size()-1);
		MetaDataDtl dataDtl      = new MetaDataDtl();
		ArrayList<FilterInfo> filterList = new ArrayList<FilterInfo>();		
		gridNGraphMeataDataMap = dataDtl.getGridNMapMetData(jsonObjMetaData,viewOptionSelectd);		
		final LinkedHashMap<String, ArrayList<String>> datsSourceDtlMap = (LinkedHashMap) gridNGraphMeataDataMap.get("datSrc");		
		getDataMap(datsSourceDtlMap);
	}
	
	public void getDataMap(final LinkedHashMap<String, ArrayList<String>> datsSourceDtlMap)
	{
		final LinkedHashMap<String, JSONObject> componentDataMap = new LinkedHashMap<String, JSONObject>();
		for (Map.Entry<String, ArrayList<String>> entry : datsSourceDtlMap.entrySet())
		{
			final String key     = entry.getKey();
			List<String> values  = entry.getValue();
			String dbDataSource  = values.get(0);
			String servletname   = values.get(1);
			String objActionPath = "";
			String page = parameterList.get(0);			
			String append="";
			if (page.equals("sales"))
			{
				objActionPath = "/ibase/" + servletname + "?month=" + parameterList.get(1) + "&dataSourceName=" + dbDataSource;
			} else if (page.equals("expense"))
			{
				objActionPath = "/ibase/" + servletname + "?month=" + parameterList.get(1) + "&dataSourceName=" + dbDataSource;
			} else if (page.equals("topbrand"))
			{
				objActionPath = "/ibase/" + servletname + "?topNos=" + parameterList.get(1) + "&month=" + parameterList.get(2) + "&dataSourceName=" + dbDataSource;
			} else if (page.equals("recall"))
			{
				objActionPath = "/ibase/" + servletname + "?days=" + parameterList.get(1) + "&dataSourceName=" + dbDataSource;
			} else if (page.equals("rcp"))
			{
				objActionPath = "/ibase/" + servletname + "?dataSourceName=" + dbDataSource + "&days=" + parameterList.get(1);
			} else if (page.equals("qc"))
			{
				objActionPath = "/ibase/" + servletname + "?geoLocation=" + parameterList.get(1) + "&month=" + parameterList.get(2) + "&dataSourceName=" + dbDataSource;
			} else if (page.equals("bspl"))
			{
				objActionPath = "/ibase/" + servletname + "?sitecode=" + parameterList.get(1) + "&acctprd=" + parameterList.get(2) + "&prdfrom=" + parameterList.get(3) + "&prdto=" + parameterList.get(4) + "&formatcode=" + parameterList.get(5) + "&reporttype=" + parameterList.get(6) + "&dataSourceName=" + dbDataSource;
			} else if (page.equals("msrscore"))
			{
				objActionPath = "/ibase/" + servletname + "?territory=" + parameterList.get(1) + "&salesperson=" + parameterList.get(2) + "&month=" + parameterList.get(3) + "&year=" + parameterList.get(4) + "&dataSourceName=" + dbDataSource;
			} else if (page.equals("dqsa"))
			{
					
					objActionPath = "/ibase/" + servletname + "?&dataSourceName=" + dbDataSource;
			}
			
			
			
			// start Add dashboard mapping for OTC dashboard on dated 15-oct-2004
			
			else if (page.equals("rsrscore"))
			{
				objActionPath = "/ibase/" + servletname + "?salesperson=" + parameterList.get(1) + "&month=" + parameterList.get(2) + "&year=" + parameterList.get(3) + "&dataSourceName=" + dbDataSource  + "&reportName="+page;
			} 
			else if (page.equals("rsrsurvey"))
			{
				objActionPath = "/ibase/" + servletname + "?salesperson=" + parameterList.get(1) + "&month=" + parameterList.get(2) + "&year=" + parameterList.get(3) + "&dataSourceName=" + dbDataSource + "&reportName="+page;
			}else if (page.equals("rxsurvey"))
			{
				objActionPath = "/ibase/" + servletname + "?salesperson=" + parameterList.get(1) + "&month=" + parameterList.get(2) + "&year=" + parameterList.get(3) + "&brand=" + parameterList.get(4) + "&dataSourceName=" + dbDataSource + "&reportName="+page;
			}else if (page.equals("outletsvisit"))
			{
				objActionPath = "/ibase/" + servletname + "?salesperson=" + parameterList.get(1) + "&month=" + parameterList.get(2) + "&year=" + parameterList.get(3) + "&dataSourceName=" + dbDataSource + "&reportName="+page;
			}else if (page.equals("doctorsvisit"))
			{
				objActionPath = "/ibase/" + servletname + "?salesperson=" + parameterList.get(1) + "&month=" + parameterList.get(2) + "&year=" + parameterList.get(3) + "&dataSourceName=" + dbDataSource + "&reportName="+page;
			}
			else if (page.equals("customerinfo"))
			{
				objActionPath = "/ibase/" + servletname + "?custCode=" + parameterList.get(1) + "&prdCode=" + parameterList.get(2)  + "&dataSourceName=" + dbDataSource+"&reportName="+page;
			}
			//end Add dashboard mapping for OTC dashboard on dated 15-oct-2004
			
			
			RequestBuilder reqBuilder = new RequestBuilder(RequestBuilder.POST, objActionPath);
			try
			{
				reqBuilder.sendRequest(null, new RequestCallback()
				{
					@Override
					public void onResponseReceived(Request request, Response response)
					{
						if (STATUS_CODE_OK == response.getStatusCode())
						{
							if (response.getText().trim().length() > 2)
							{
								JSONObject servletJsnObj = (JSONObject) JSONParser.parseStrict(response.getText());
								JSONObject jsonObjData  = new JSONObject();
								jsonObjData.put(key, servletJsnObj);								
								componentDataMap.put(key, jsonObjData);
								if (componentDataMap.size() == datsSourceDtlMap.size())
								{			
									buildChart(componentDataMap);
								} 
							}
						} else
						{
							Window.alert("Responce for getData null");
						}
					}

					@Override
					public void onError(com.google.gwt.http.client.Request request, Throwable exception)
					{
						Window.alert("Error occured :: GraphComponent : getData()  " + exception.getMessage());
					}
				});
			} catch (RequestException e)
			{
				e.printStackTrace();
			}
		}
	}

	
	public boolean isNumeric(String s) {  
	    return s.matches("[-+]?\\d*\\.?\\d+");  
	}
}
