package ibase.client;


import java.util.ArrayList;
import java.util.HashMap;

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.json.client.JSONString;

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.Label;
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;



/**
 * 
 * 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>();
	HashMap<String, ArrayList<String>>  graphCaptioneMap=null;
	ArrayList<String>  graphCaptionList= new ArrayList<String>();
	/**
	 * This constructor initializes the graphcontainer
	 * 
	 */
	
	/*Start code for progess bar to data building- Dhanendra 17Nov2014*/
	protected E12LoadingInterface e12LoadImg=new E12LoadingInterface();
	/*End code for progess bar to data building- Dhanendra 17Nov2014*/
	public GraphComponent(ArrayList<String> parameterList, JSONObject metaDataJsnObj)
	{
		String isShowfilter= Window.Location.getParameter("FLAG");
		this.jsonObjMetaData = metaDataJsnObj;
		this.parameterList = parameterList;
		mainContainer.setWidth("100%");
		if(! ("N").equalsIgnoreCase(isShowfilter)){
		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;
		ScrollPanel scrlPanel = null;
		FlexTable flexTable   = null;
		String caption = "";
		
		JSONObject graphJson = null;
		final String componentType = "componentType";
		String compType = "";
		String component ="";
		HashMap<String, ArrayList<String>> graphTypeMap = null;
		String dtSrouce="";
		
		/** Add Code By Dhanendra for No Data Found Msg **/
		String parameter="";
		boolean isParameter = false;
		for (int i = 0; i < parameterList.size(); i++)
        {
			if(i<parameterList.size()-1 && i!=0)
			{
				parameter = parameterList.get(i);
				if(parameter.trim().length() !=0)
				{
					isParameter = true;
				}
				
			}
	    }
		/** End Code By Dhanendra for No Data Found Msg **/
		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>();
		}
		/*if(dataMap.toString().length()>20) //if loop for no data found alert
		{*/  // for only OTC 
		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))
				{
					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);
						// start- added empty json chartdata to display no data found message by swati on 7jan2015 
						if(graphJson.size()==0 )
						{
							graphJson.put("chart", new JSONString(""));
						}
						// end- added empty json chartdata to display no data found message by swati on 7jan2015 
						if (graphJson != null && graphJson.size() > 0)
						{
							this.createChart(graphJson.toString().replace('@', '='), "chartContainer" + componentId, "chartContainer" + componentId, width, height, imageName);
						}
					}
				} 
				else if("T".equalsIgnoreCase(type))
				{
					if(jsonObjFrGraph != null)
					{
					RootPanel.get("chartContainer"+componentId).clear();
					//RootPanel.get().clear();
					scrlPanel = new ScrollPanel();
					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(scrlPanel);
						RootPanel.get("chartContainer"+componentId).add(horizontalPnl);
				
					} else if("DataGrid".equalsIgnoreCase(component))
					{ 
						flexTable       = new FlexTable();
						CustomGrid data = new CustomGrid(8);
						flexTable       = data.jsonToArrayList(gridNGraphMeataDataMap, jsonObjFrGraph,dtSrouce,componentId);
						Button excelBtn = new Button("Export To Excel");
						excelBtn.setTitle("Excel");
						RootPanel.get("chartContainer"+componentId).add(flexTable);
					}
					}
					/** Start Code By Dhanendra for No Data Found Msg - 08 Dec 2014 **/
					else 
					{
						RootPanel.get("chartContainer"+componentId).clear();
						if(isParameter)
						{	
							flexTable       = new FlexTable();
							graphCaptionList.clear();
							graphCaptioneMap = gridNGraphMeataDataMap.get("componentCaption"+componentId);
							graphCaptionList.add(""+graphCaptioneMap.get("componentCaption"+componentId));
							caption = graphCaptionList.get(0); 
							Label labelNoDataFound = new Label("No Data Found");
							if(caption !=null && caption.trim().length()>0)
							{
								flexTable.setText(0, 0, caption);
								flexTable.setWidget(1, 0, labelNoDataFound);
								flexTable.getCellFormatter().setStyleName(0 ,0 , "FlexTable-ColumnHeaderCell");
								flexTable.getCellFormatter().setStyleName(1 ,0 , "gwt-ScrollTable");
							}else
							{
								flexTable.setWidget(0, 0, labelNoDataFound);
								flexTable.getCellFormatter().setStyleName(0 ,0 , "gwt-ScrollTable");	
							}
							flexTable.setStyleName("flexCSS");
							RootPanel.get("chartContainer"+componentId).add(flexTable);
						}
					}
					/** End Code By Dhanendra for No Data Found Msg **/
				}
				if ("H".equalsIgnoreCase(type))
				{
					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.buildHeatMap(graphDtlList, jsonObjFrGraph, dtSrouce);						// start- added empty json chartdata to display no data found message by swati on 7jan2015 
						if(graphJson.size()==0 )
						{
							graphJson.put("chart", new JSONString(""));
						}
						// end- added empty json chartdata to display no data found message by swati on 7jan2015 
						if (graphJson != null && graphJson.size() > 0)
						{
							this.createChart(graphJson.toString().replace('@', '='), "chartContainer" + componentId, "chartContainer" + componentId, width, height, imageName);
						}
					}
				} 
			}
		}
		e12LoadImg.setLoading(false);
		/*}else
		{
			Window.alert("No Data Found");
		}*/
	}
    
	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>();
		if(parameterList.get(1).trim().length()>0 || parameterList.get(1).trim()!="")
		 {
			e12LoadImg.setLoadingInfo("Waiting For Data...");
			e12LoadImg.setLoading(true);
		 }
		
		ArrayList<FilterInfo> filterList = new MetaDataDtl().getFilters(jsonObjMetaData);
		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);
			FilterInfo filterInfo = null;
			
			/** Start Added New code By sachin for Creating Dynamic Url For Report  on 04/12/14**/
			objActionPath = "/ibase/" + servletname;
			int cnt=0;
			for (int i = 0; i < filterList.size(); i++)
			{
				cnt++;
				filterInfo = filterList.get(i);
				if(i==0)
				{
					objActionPath=objActionPath + "?" + filterInfo.getName()+"="+parameterList.get(cnt);
				}else
				{
					objActionPath=objActionPath + "&" + filterInfo.getName()+"="+parameterList.get(cnt);
				}
			}
			objActionPath=objActionPath+"&dataSourceName=" + dbDataSource + "&reportName="+page;
			
			/** End Added New code By sachin for Creating Dynamic Url For Report  on 04/12/14**/
			
			
			/*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("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+ "&reportName="+page;
			}
			
			
			
			// 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) + "&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;
			}
			
			//end Add dashboard mapping for OTC dashboard on dated 15-oct-2004
			Start Add For SUN Dashboard
			else if (page.equals("customerinfo"))
			{
				objActionPath = "/ibase/" + servletname + "?custCode=" + parameterList.get(1) + "&prdCode=" + parameterList.get(2)  + "&dataSourceName=" + dbDataSource+"&reportName="+page;
			}
			else if (page.equals("ordershipment"))
			{
				objActionPath = "/ibase/" + servletname + "?lastMonth=" + parameterList.get(1)+"&siteCode=" + parameterList.get(2) + "&custCode=" + parameterList.get(3) + "&custCodeDlv=" + parameterList.get(4) +"&dataSourceName=" + dbDataSource+"&reportName="+page;
			}
			
			End  For SUN Dashboard
			Start Add For MFG SUN Dashboard
			else if (page.equals("recall"))
			{
				objActionPath = "/ibase/" + servletname + "?lastMonth=" + parameterList.get(1) + "&dataSourceName=" + dbDataSource;
			}
			else if (page.equals("rcp"))
			{
				objActionPath = "/ibase/" + servletname + "?lastMonth=" + parameterList.get(1) + "&dataSourceName=" + dbDataSource;
			}
			else if (page.equals("qc"))
			{
				objActionPath = "/ibase/" + servletname + "?geoLocation=" + parameterList.get(1) + "&lastMonth=" + parameterList.get(2) + "&dataSourceName=" + dbDataSource;
			}*/
			/*END For MFG SUN Dashboard*/
			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) //if code is relese to OTC then Comment this if condition Dhanendra 07Nov2014
							{ 
								JSONObject servletJsnObj = (JSONObject) JSONParser.parseStrict(response.getText());
								JSONObject jsonObjData  = new JSONObject();
								jsonObjData.put(key, servletJsnObj);								
								componentDataMap.put(key, jsonObjData);
							}else
							{
								componentDataMap.put(key, null);
								RootPanel.get("chartContainer"+key).clear();
							}
							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();
				e12LoadImg.setLoading(false);
			}
		}
	}
	public boolean isNumeric(String s) {  
	    return s.matches("[-+]?\\d*\\.?\\d+");  
	}
}
