<%@ include file= "ErReporterTracker.jsp" %>
<%@ page import = "java.util.Date"%>
<%@	page import	= "java.text.DateFormat" %>
<%@ page import = "java.text.SimpleDateFormat"%>
<%@ page import = "java.util.Enumeration"%>
<%@ page import = "net.sf.json.*" %>
<%@ page import = "com.eg.*" %>
<%@ page import = "com.eg.EgMappingInfo" %>
<%@ page import = "com.eg.IniFile" %>
<%@ page import = "com.egurkha.ini.IniUI" %>
<%@ page import = "egurkha.reporter.*"%>
<%@ page import = "egurkha.reporter.builder.InfoHandler"%>
<%@ page import = "egurkha.reporter.builder.TemplateInfoBean"%>
<%@ page import = "egurkha.reporter.builder.ReportTemplateBean"%>
<%@ page import = "egurkha.reporter.builder.ReportBuilderBean"%>
<%@ page import = "java.io.DataOutputStream"%>
<%@ page import = "java.io.FileNotFoundException"%>
<%@ page import = "java.io.FileOutputStream"%>
<%@ page import = "java.io.IOException"%> 
<%@ taglib prefix="egui" uri="../WEB-INF/eg-taglib.tld"%>
<%@ page language="java" contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" %>
 

<%
try
{
	HashMap changeFnNames=new HashMap();
	changeFnNames.put("Raw","No Calculation");
	changeFnNames.put("Current","Latest Data");
	String queryString,method; 
	JSONObject templateJson = new JSONObject();
	method	=	request.getParameter("method");
	String builderType	=	request.getParameter("builderType");
	queryString =(String)ErUtils.prepareQueryString(request.getParameterMap());	
	String sessionId=session.getId();
	InfoHandler infoHandler=new InfoHandler(2);//.. for getting measure unit
	String errorMsg = "Please add/configure the widget(s)";
	String iniFileName="eg_reportbuilder";
	ErUtils erUtils = new ErUtils();
	
	if(method!=null)
	{
		ReportBuilderBean reportBean= new ReportBuilderBean(sessionId,urs);
		boolean clusterSupported = false;
		if(EgInstallInfo.isClusterSupported)
			clusterSupported=true;
		boolean isSecondaryManager=false;
		EgManagersIniForManager managersIni = null;
		if(clusterSupported)
		{			
			managersIni = EgManagersIniForManager.getInstance();
			if(!managersIni.isPrimaryManager())
				isSecondaryManager=!managersIni.isPrimaryManager();
		}
		if(method.equals("getTemplateInfo"))
		{
			String recordInfo = request.getParameter("recordInfo");
			JSONObject templateInfoObj = (JSONObject) JSONSerializer.toJSON(recordInfo);
			//System.out.println("[ReportBuikderController] recordInfo >>>>> "+recordInfo);
			TemplateInfoBean templateInfoBean=(TemplateInfoBean) JSONObject.toBean(templateInfoObj, TemplateInfoBean.class);

			IniFile inifile = new IniFile(EgInstallInfo.getInstallDir()+"/manager/config/"+iniFileName+".ini");
			String templateDetailsVariable=inifile.getValue("custom_Reports",templateInfoBean.getTemplateName());
			String overviewTemplateName=templateDetailsVariable.substring(0,templateDetailsVariable.indexOf(','));
			String detailviewTemplateName=templateDetailsVariable.substring(templateDetailsVariable.indexOf(',')+1);
			
			if(overviewTemplateName !=null && detailviewTemplateName!=null)
			{
				List vList =new ArrayList(Arrays.asList(inifile.getVariables(overviewTemplateName)));
				for(int i=0;i<vList.size();i++)
				{
					String var=(String)vList.get(i);
					String value=inifile.getValue(overviewTemplateName,var);
					if(var.equals("chartInfo")||var.startsWith("widgetInfo")|| var.startsWith("ddRawConfigString"))
					{
						templateInfoObj.put(var,JSONSerializer.toJSON(value));
					}
					else
					{
						templateInfoObj.put(var,value);
					}					
				}
				//System.out.println("==templateInfoObj===>>..>>>"+templateInfoObj);
				String isCustomLayout=inifile.getValue(overviewTemplateName,"isCustomLayout");
				if(isCustomLayout!=null)
				{
					String language = thisuser.getLanguage();
					EgMappingInfo intlmap = new EgMappingInfo(language);
					vList =new ArrayList(Arrays.asList(inifile.getVariables(detailviewTemplateName)));
					if(isCustomLayout.equals("no"))
					{
						
						ArrayList removableMesList = new ArrayList();
						JSONObject iniChartInfo =(JSONObject) JSONSerializer.toJSON(inifile.getValue(overviewTemplateName,"chartInfo"));
						//System.out.println("iniChartInfo   "+iniChartInfo);
						JSONArray ddChkBoxAry = new JSONArray();
						JSONObject ddGroupByMeasure=(JSONObject)iniChartInfo.get("ddGroupByMeasure");
						if(ddGroupByMeasure!=null)
						{
							Iterator itr = ddGroupByMeasure.entrySet().iterator();
							while(itr.hasNext())
							{
								Map.Entry entry= (Map.Entry)itr.next();
								String mesDisplayName=(String)entry.getKey();
								JSONArray ddMesArry = (JSONArray)ddGroupByMeasure.get(mesDisplayName);
								JSONObject ddChkBoxObj = new JSONObject();
								String chkBoxValue="";
								for(int i=0;i<ddMesArry.size();i++)
								{
									String tempStr=(String)ddMesArry.get(i);
									tempStr=tempStr.substring(tempStr.indexOf("=")+1,tempStr.length());
									removableMesList.add(tempStr);
									String chkBoxTempValue=tempStr.substring(tempStr.indexOf("|")+1,tempStr.length());
									//System.out.println(chkBoxTempValue);
									//StringTokenizer tokens = new StringTokenizer(chkBoxTempValue,"$~$");
									ArrayList tokens=ErUtils.egTokenizer(chkBoxTempValue,"$~$");
									//String[] chkBoxTempValueAry=chkBoxTempValue.split("$~$");
									////System.out.println(chkBoxTempValueAry.length);
									//System.out.println(chkBoxTempValueAry[0]);
									//chkBoxValue=chkBoxValue+tokens.nextToken()+"$~$"+tokens.nextToken();
									chkBoxValue=chkBoxValue+(String)tokens.get(0)+"$~$"+(String)tokens.get(1);
									if(i<ddMesArry.size()-1)
									{
										chkBoxValue=chkBoxValue+",";
									}
									//ADAcMgmtEvtTest_DDD|msmt_time$~$EvtType(Min)msmt_time$~$None$~$0|-1|Raw
								}
								ddChkBoxObj.put("id",mesDisplayName);
								ddChkBoxObj.put("value",chkBoxValue);
								ddChkBoxAry.add(ddChkBoxObj);
							}
						}
						templateInfoObj.put("ddChkBoxData",ddChkBoxAry);
						//System.out.println(removableMesList);
						JSONArray rows=new JSONArray();
						for(int i=0;i<vList.size();i++)
						{
							String componentType=(String)vList.get(i);
							String componentTypeInfos=inifile.getValue(detailviewTemplateName,componentType);
							List componentTypeInfosList=getListForTokens(componentTypeInfos,"*");
							for(int j=0;j<componentTypeInfosList.size();j++)
							{
								String componentTypeInfo=(String)componentTypeInfosList.get(j);
								if(removableMesList.contains(componentTypeInfo))
								{
									continue;
								}
								//System.out.println("===componentTypeInfo===>>>sdd>>"+componentTypeInfo);
								List componentTypeInfoList=getListForTokens(componentTypeInfo,"|");
								String test=(String)componentTypeInfoList.get(0);
								String testValue=(String)componentTypeInfoList.get(0);
								String er_testType="Measures";
								if(test.endsWith("_DDD"))
								{
									er_testType="Details";
									test=test.substring(0,test.indexOf("_DDD"));
								}
								String measure=(String)componentTypeInfoList.get(1);
								String displayName=null;
								String glduration=null;
								String er_duration=null;
								
								//int ms=0;
								//StringTokenizer token=new StringTokenizer(measure, "$~$");
								ArrayList token=ErUtils.egTokenizer(measure, "$~$");
								/*while(token.hasMoreTokens())
								{
									String mesStr=token.nextToken();
									if(ms<=1)
									{
										displayName=mesStr;
									}
									if(ms==0)
										measure=mesStr;	
									if(ms==2)
										glduration=mesStr;
									if(ms==3)
										er_duration=mesStr;
									ms++;
								}*/
								for(int ms=0;ms<token.size();ms++)
								{
									String mesStr=(String)token.get(ms);
									if(ms<=1)
									{
										displayName=mesStr;
									}
									if(ms==0)
										measure=mesStr;	
									if(ms==2)
										glduration=mesStr;
									if(ms==3)
										er_duration=mesStr;
								}
								String infos=(String)componentTypeInfoList.get(2);
								if(infos!=null && infos.equals("-1")){
									infos="-";
								}
								String unit=infoHandler.getEgTablesInfo().getUnitForMeasure(test,measure);//.. for grid measure unit
								String function=(String)componentTypeInfoList.get(3); 
								
								String configString="comptypeid"+componentType+"="+componentTypeInfo;
								JSONObject row=new JSONObject();
								row.put("componentType",intlmap.getComponentTypeDescription(componentType));
								row.put("test",intlmap.getTestDescription(test));
								if(unit != null && unit.length()>0)
									row.put("measure",intlmap.getMeasureDescription(test,measure)+" ("+unit+")");
								else
									row.put("measure",intlmap.getMeasureDescription(test,measure));
								if(changeFnNames.get(function)!=null)
								{
									function=(String)changeFnNames.get(function);
								}
								String displayMesDes=intlmap.getMeasureDescription(test,displayName);
								row.put("displayName",displayMesDes);
								row.put("displayNameDummy",displayName.substring(0,displayName.indexOf("(")));
								row.put("er_testType",er_testType);
								row.put("descriptor",infos);
								row.put("testValue",testValue);
								row.put("measureValue",measure);
								row.put("function",function);
								row.put("configString",configString);
								row.put("glduration",glduration);
								row.put("er_duration",er_duration);
								if(ddGroupByMeasure==null||ddGroupByMeasure.get(displayMesDes)==null)
									row.put("ddconfigString","");
								else{
									String ddconfigString="";
									JSONArray ddMesConfigStrArry = (JSONArray)ddGroupByMeasure.get(displayMesDes);
									for(int ii=0;ii<ddMesConfigStrArry.size();ii++)
									{
										String tempConfigStr=(String)ddMesConfigStrArry.get(ii);
										ddconfigString=ddconfigString+"comptypeid"+tempConfigStr;
										if(ii<ddMesConfigStrArry.size()-1)
										{
											ddconfigString=ddconfigString+"*";
										}
									//	removableMesList.add(tempStr);
									}
											row.put("ddconfigString",ddconfigString);
								}
								rows.add(row);
							} 
							JSONArray ddRawConfigArray=(JSONArray)templateInfoObj.get("ddRawConfigString");
							for(int j=0;j<ddRawConfigArray.size();j++)
							{
								String ddRawConfigInfoStr=(String)ddRawConfigArray.get(j);
								int index=ddRawConfigInfoStr.indexOf("=");
								componentType=ddRawConfigInfoStr.substring(0,index);
								ddRawConfigInfoStr=ddRawConfigInfoStr.substring(index+1);

								List ddRawConfigInfoList=getListForTokens(ddRawConfigInfoStr,"|");

								String test=(String)ddRawConfigInfoList.get(0);
								String testValue=(String)ddRawConfigInfoList.get(0);
								String er_testType="Measures";
								if(test.endsWith("_DDD"))
								{
									er_testType="Details";
									test=test.substring(0,test.indexOf("_DDD"));
								}
								String measure=(String)ddRawConfigInfoList.get(1);
								String displayName=null;
								String glduration=null;
								String er_duration=null;
								/*int ms=0;
								StringTokenizer token=new StringTokenizer(measure, "$~$");
								while(token.hasMoreTokens())
								{
									String mesStr=token.nextToken();
									if(ms<=1)
									{
										displayName=mesStr;
									}	
									if(ms==0)
										measure=mesStr;	
									if(ms==2)
										glduration=mesStr;
									if(ms==3)
										er_duration=mesStr;
									ms++;
								}*/
								ArrayList token=ErUtils.egTokenizer(measure, "$~$");
								for(int ms=0;ms<token.size();ms++)
								{
									String mesStr=(String)token.get(ms);
									if(ms<=1)
									{
										displayName=mesStr;
									}	
									if(ms==0)
										measure=mesStr;	
									if(ms==2)
										glduration=mesStr;
									if(ms==3)
										er_duration=mesStr;
								}
								String infos=(String)ddRawConfigInfoList.get(2);
								if(infos!=null && infos.equals("-1")){
									infos="-";
								}
								String unit=infoHandler.getEgTablesInfo().getUnitForMeasure(test,measure);//.. for grid measure unit
								String function=(String)ddRawConfigInfoList.get(3); 
								String configString="comptypeid"+componentType+"="+ddRawConfigInfoStr;
								JSONObject row=new JSONObject();
								row.put("componentType",intlmap.getComponentTypeDescription(componentType));
								row.put("test",intlmap.getTestDescription(test));
								if(unit != null && unit.length()>0){
									row.put("measure",intlmap.getMeasureDescription(test,measure)+" ("+unit+")");
								}else{
									row.put("measure",intlmap.getMeasureDescription(test,measure));
								}
								if(changeFnNames.get(function)!=null)
								{
									function=(String)changeFnNames.get(function);
								}
								row.put("displayName",intlmap.getMeasureDescription(test,displayName));
								row.put("displayNameDummy",displayName.substring(0,displayName.indexOf("(")));
								row.put("measureValue",measure);
								row.put("descriptor",infos);
								row.put("testValue",testValue);
								row.put("function",function);
								row.put("er_testType",er_testType);
								row.put("configString",configString);
								row.put("glduration",glduration);
								row.put("er_duration",er_duration);
								row.put("ddconfigString","");
								rows.add(row);
							}
						}
						templateInfoObj.put("configGridData", rows);
						//System.out.println("====normal end==templateInfoObj==>>>"+templateInfoObj);
					}
					else
					{
						templateJson.put("status", "modify is under progress for customlayout");
						for(int i=0;i<vList.size();i++)
						{
							String widgetComtTypeStr=(String)vList.get(i);
							String widgetCompTypeInfos=inifile.getValue(detailviewTemplateName,widgetComtTypeStr);
//							int index=widgetComtTypeStr.indexOf("~");
							int index=widgetComtTypeStr.indexOf("$");
							String widget=widgetComtTypeStr.substring(0,index);  
							String componentType=widgetComtTypeStr.substring(index+1);
							JSONObject widgetObj=(JSONObject)templateInfoObj.get(widget);
							
							JSONArray ddChkBoxAry = new JSONArray();
							ArrayList removableMesList = new ArrayList();
							JSONObject ddGroupByMeasure=(JSONObject)widgetObj.get("ddGroupByMeasure");
					
							if(ddGroupByMeasure!=null)
							{
								Iterator itr = ddGroupByMeasure.entrySet().iterator();
								while(itr.hasNext())
								{
									Map.Entry entry= (Map.Entry)itr.next();
									String mesDisplayName=(String)entry.getKey();
									JSONArray ddMesArry = (JSONArray)ddGroupByMeasure.get(mesDisplayName);
									JSONObject ddChkBoxObj = new JSONObject();
									String chkBoxValue="";
									for(int j=0;j<ddMesArry.size();j++)
									{
										String tempStr=(String)ddMesArry.get(j);
										tempStr=tempStr.substring(tempStr.indexOf("=")+1,tempStr.length());
										removableMesList.add(tempStr);
										String chkBoxTempValue=tempStr.substring(tempStr.indexOf("|")+1,tempStr.length());
										//System.out.println(chkBoxTempValue);
										//StringTokenizer tokens = new StringTokenizer(chkBoxTempValue,"$~$");
										ArrayList tokens=ErUtils.egTokenizer(chkBoxTempValue,"$~$");
										//String[] chkBoxTempValueAry=chkBoxTempValue.split("$~$");
										//System.out.println(chkBoxTempValueAry.length);
										//System.out.println(chkBoxTempValueAry[0]);
										//chkBoxValue=chkBoxValue+tokens.nextToken()+"$~$"+tokens.nextToken();
										chkBoxValue=chkBoxValue+(String)tokens.get(0)+"$~$"+(String)tokens.get(1);
										if(j<ddMesArry.size()-1)
										{
											chkBoxValue=chkBoxValue+",";
										}
										//ADAcMgmtEvtTest_DDD|msmt_time$~$EvtType(Min)msmt_time$~$None$~$0|-1|Raw
									}
									ddChkBoxObj.put("id",mesDisplayName);
									ddChkBoxObj.put("value",chkBoxValue);
									ddChkBoxAry.add(ddChkBoxObj);
								}
							}
							widgetObj.put("ddChkBoxData",ddChkBoxAry);

							String infoLabel = inifile.getValue(templateInfoBean.getTemplateName()+"_displayView",widget+"*$*info");

							JSONArray rows=getConfig(widgetCompTypeInfos,componentType,intlmap,changeFnNames,removableMesList,ddGroupByMeasure);
							
							if(widgetObj.containsKey("chartConfigArray"))
							{
								JSONArray configGridDataArray=(JSONArray)widgetObj.get("chartConfigArray"); 
								configGridDataArray.addAll(rows);
							}
							else
							{
								widgetObj.put("chartConfigArray",rows);
							}
							JSONArray totalMesAry = getTotalMes(widgetCompTypeInfos, componentType, intlmap, changeFnNames, removableMesList, ddGroupByMeasure, widgetObj, infoLabel,infoHandler);
							
							if(widgetObj.containsKey("editableObj"))
							{
								JSONArray tabDataArray=(JSONArray)widgetObj.get("editableObj"); 
								tabDataArray.addAll(totalMesAry);
							}
							else
							{
								widgetObj.put("editableObj",totalMesAry);
							}

							
						}
						// add ddRaw Config
						JSONArray widgetList=(JSONArray)templateInfoObj.get("widgetList");
						for(int i=0;i<widgetList.size();i++)
						{
							String widget=(String)widgetList.get(i);
							JSONArray ddRawConfigArray=(JSONArray)templateInfoObj.get(widget+"_ddRaw");
							JSONObject widgetObj=(JSONObject)templateInfoObj.get(widget);
							JSONArray rows=getDDConfig(ddRawConfigArray,intlmap,changeFnNames);
							JSONArray configGridDataArray=(JSONArray)widgetObj.get("chartConfigArray");
							if(configGridDataArray != null) //...
								configGridDataArray.addAll(rows);
						}
					}
					templateJson.put("status", "success"); 
					request.setAttribute("userId",urs);
					request.setAttribute("sessionId",session.getId());
					ReportTemplateBean templateBean=new ReportTemplateBean(request);	 
					templateJson.put("combo", templateBean.getCombos());
					templateJson.put("selectedFields", templateBean.getSelectedFields());
					templateJson.put("displayFields", templateBean.getDisplayFields());
					templateJson.put("templateInfo", templateInfoObj); 
				}
				else
				{
					templateJson.put("status", "modify is under progress for customlayout");
				}
			}
			else
			{
				templateJson.put("status", "Template info for "+templateInfoBean.getTemplateName()+" is not found");
			}
		}
		else if(method.equals("getini"))
		{
			IniFile iniFile = new IniFile(EgInstallInfo.getInstallDir()+"/manager/config/"+iniFileName+".ini");			
			templateJson.put("status", "success");		
			JSONArray getGridData=getIni(iniFile,reportBean,sessionId,urs,builderType);
			JSONArray listViewData=new JSONArray();
			listViewData=getGridData;
			//System.out.println("===listViewData===>>>..>>>"+listViewData);
			for(int jk=0;jk<listViewData.size();jk++)
			{
				JSONObject dataObj = (JSONObject)listViewData.get(jk);
				String templateDesc=(String)dataObj.get("templateDescription");
				String templateNameDisp_=(String)dataObj.get("templateNameDisp");
				templateNameDisp_ = erUtils.specialCharDecode(templateNameDisp_);
				dataObj.put("templateNameDisp",templateNameDisp_);
				if(templateDesc!=null&&templateDesc.length()>150)
				{
					templateDesc=templateDesc.substring(0,150)+"...";
				}
				dataObj.put("templateDescDisplay",templateDesc);
				dataObj.put("disbleFlag",true);
				dataObj.put("deleteUrl","");
				dataObj.put("Delete","Delete");
				dataObj.put("EditSettings","Edit Settings");
				dataObj.put("Generate","Generate");
				dataObj.put("templateImg","../images/"+thisuser.getReporterSkin()+"/listViewWidgetDefault.png");
				
				if((String)dataObj.get("modifiedDate")==null)
					dataObj.put("modifiedDate","");
				if((String)dataObj.get("builderConfigString")==null)
					dataObj.put("builderConfigString","");
				if((String)dataObj.get("disbleStatus")==null)
				{
					dataObj.put("disbleStatus","");
					dataObj.put("disbleFlag",false);
				}
				if(dataObj.get("disableModifyDelete") != null && dataObj.get("disableModifyDelete").toString().equals("true"))
					dataObj.put("disbleFlag",true);
				if((String)dataObj.get("sharedBy")!=null&&((String)dataObj.get("sharedBy")).equalsIgnoreCase("Own"))
				{
					dataObj.put("isShareByOwn",true);
				}else
					dataObj.put("isShareByOwn",false);

				if((String)dataObj.get("sharing")!=null&&((String)dataObj.get("sharing")).equalsIgnoreCase("Private"))
				{
					dataObj.put("isShared",false);
				}else
					dataObj.put("isShared",true);

			}
			templateJson.put("listViewData", listViewData);
			templateJson.put("gridData", getGridData);
			templateJson.put("dummyGraphData", this.getDummyGraphData());
		}
		else if(method.equals("setini"))
		{
			String accessType = request.getParameter("sharing");
			String template_name=request.getParameter("templateName");
			String userList=request.getParameter("userList");
			String isEditTemplate=request.getParameter("isEditTemplate");
			//System.out.println("=====isEditTemplate======jsp=>>>"+isEditTemplate);
			Map requestMap = request.getParameterMap();
			//ReportBuilderBean builderBean=new ReportBuilderBean(sessionId,urs,template_name,accessType,userList,requestMap);
			if(template_name.indexOf(".")>-1)
			{
				template_name = template_name.substring(template_name.lastIndexOf(".")+1);
			}
			template_name = urs+"."+template_name;
			templateJson.put("templateName", template_name);
			if(isEditTemplate != null && isEditTemplate.equalsIgnoreCase("true"))
			{
				boolean deleteStatus=reportBean.deleteTemplateFromDb(sessionId,urs,template_name);
				if(deleteStatus)
					reportBean.insertTemplateIntoDb(urs,template_name,accessType,userList,requestMap,isEditTemplate);	
			}
			else
				reportBean.insertTemplateIntoDb(urs,template_name,accessType,userList,requestMap,isEditTemplate);

			IniFile iniFile = new IniFile(EgInstallInfo.getInstallDir()+"/manager/config/"+iniFileName+".ini",true);
			
			HashMap dispMp=(HashMap)session.getAttribute("dispMp");
			
			//System.out.println("=dispMp=====>>>>>>>>>"+dispMp);
			String isCustomLayout=request.getParameter("isCustomLayout");
			try{
				if(dispMp != null)
				{
					Iterator itr1 = dispMp.entrySet().iterator();
					if(isCustomLayout.equals("yes"))
					{				
						while(itr1.hasNext())
						{
							Map.Entry entry1 = (Map.Entry)itr1.next();	
							String idDescription=(String)entry1.getKey();
							String keyVal=(String) dispMp.get(idDescription);
							String[] keySplit=(String[]) idDescription.split("\\*\\*");
							if(keySplit!=null && keySplit.length>0)
							{
								for(int i=0;i<keySplit.length;i++)
								{
									String meskey="";
									String keySub="";
									String widId="";
									String keyDesc="";	
									keySub=(String) keySplit[0];							
									widId=(String) keySplit[1];							
									keyDesc=(String) keySplit[2];
									if(keyDesc!=null && keyDesc.indexOf("_")>-1)
										keyDesc=keyDesc.substring(0,keyDesc.lastIndexOf("_"));
									
									//meskey=widId+"*~*"+keyDesc;
									meskey=widId+"*$*"+keyDesc;//'~' symbol in ini variable is changed to '$' symbol
									iniFile.setValue(keySub+"_displayView",meskey,keyVal);							
								}
							}
						}					
					}
					else
					{				
						while(itr1.hasNext())
						{
							Map.Entry entry1 = (Map.Entry)itr1.next();	
							String idDescription=(String)entry1.getKey();
							String keyVal=(String) dispMp.get(idDescription);
							String[] keySplit=(String[]) idDescription.split("\\*\\*");
							if(keySplit!=null && keySplit.length>0)
							{
								for(int i=0;i<keySplit.length;i++)
								{
									String meskey="";
									String keySub="";
									String widId="";
									String keyDesc="";	
									keySub=(String) keySplit[0];							
									widId="widget";							
									keyDesc=(String) keySplit[1];
									if(keyDesc!=null && keyDesc.indexOf("_")>-1)
										keyDesc=keyDesc.substring(0,keyDesc.lastIndexOf("_"));
									
									//meskey=widId+"*~*"+keyDesc;
									meskey=widId+"*$*"+keyDesc;
									iniFile.setValue(keySub+"_displayView",meskey,keyVal);							
								}
							}	
						}					
					}
				}
			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
			Vector overVars=new Vector();
			Vector overVals=new Vector();
			Vector detailVars=new Vector();
			Vector detailVals=new Vector();
			Vector congigureVals=new Vector();
			Vector congigureVars=new Vector();
			Vector displayVars=new Vector();
			Vector displayVals=new Vector();
			String templateName=null;
			Enumeration ename=request.getParameterNames();			
			boolean flag=false;
			ArrayList templateList =new ArrayList(Arrays.asList(iniFile.getVariables("custom_Reports")));
			while(ename.hasMoreElements())
			{
				String enext=(String)ename.nextElement();
				//System.out.println("[Reporttemplatecontroller] enext  "+enext);
				if(enext.equals("templateName"))
				{
					templateName=(String)request.getParameter(enext);
					if(templateName.indexOf(".")>-1)
					{
						templateName = templateName.substring(templateName.lastIndexOf(".")+1);
					}
					templateName = urs+"."+templateName;
					flag=iniFile.setValue("custom_Reports", templateName, templateName+"_overview,"+templateName+"_detailview");
				}
				else
				{
					String paramVals[]=request.getParameterValues(enext);
					StringBuffer paramVal=new StringBuffer();
					for(int i=0;i<paramVals.length;i++)
					{
						String paramValTemp=paramVals[i];
						if(paramValTemp != null && paramValTemp.indexOf("EGPERCENTEG") != -1)
						{
							paramValTemp=paramValTemp.replaceAll("EGPERCENTEG","%");
						}
						paramVal.append(paramValTemp+"*");
					}
					if(enext.indexOf("comptypeid")>-1)
					{
						if(isCustomLayout.equals("yes"))
						{
							enext=enext.replace("comptypeid", "");
							//enext=enext.substring("comptypeid".length(),enext.length());
						}
						else
						{
							enext=enext.substring("comptypeid".length(),enext.length());
						}
						detailVars.add(enext);
						detailVals.add(paramVal.deleteCharAt(paramVal.length() - 1).toString());
					}
					else
					{
						String overViewVal=paramVal.deleteCharAt(paramVal.length() - 1).toString();

						overVars.add(enext);
						overVals.add(overViewVal);
						if(enext.equalsIgnoreCase("chartInfo"))
						{
							JSONObject chartInfoObj = (JSONObject)JSONSerializer.toJSON(overViewVal);
							displayVals.add(chartInfoObj.get("descDisplayName"));
							//displayVars.add("widget*~*info");
							displayVars.add("widget*$*info");
						}
					}
					
				}
			}
			
			// get configureViewInfos
			if(isCustomLayout.equals("yes"))
			{
				//System.out.println("[Reporttemplatecontroller]overVals  "+overVars);
				//System.out.println("[Reporttemplatecontroller]overVals  "+overVals);
				//System.out.println("[Reporttemplatecontroller]overVars index  "+overVars.indexOf("widgetList"));
				//System.out.println("[Reporttemplatecontroller]overVals  "+overVals.get(overVars.indexOf("widgetList")));
				// widgetInfo1*~*headerDescription=Active
				String temp= (String)overVals.get(overVars.indexOf("widgetList"));
				//JSONArray tepm1=(JSONArray)JSONSerializer.toJSON(temp);
				//System.out.println("[Reporttemplatecontroller]tepm1  "+tepm1);
				JSONArray widgetList = (JSONArray)JSONSerializer.toJSON(temp);
						//congigureVars.add("widgetOrder");
						//congigureVals.add(widgetList.toString());
				//System.out.println("[Reporttemplatecontroller]Done!");
				if(widgetList!=null)
				{
					TreeMap orderMap=new TreeMap();
					//double aDouble = Double.parseDouble(aString);
					for(int i=0;i<widgetList.size();i++)
					{
						String widgetInfoName = (String)widgetList.get(i);
						JSONObject widgetInfoObj = (JSONObject)JSONSerializer.toJSON((String)overVals.get(overVars.indexOf(widgetInfoName)));
						JSONObject configureInfo = new JSONObject();
						String position=widgetInfoObj.get("x")+",";
						String positionY=widgetInfoObj.get("y")+"";
						if(positionY.length()==1)
							positionY="0"+positionY;
						position=position+positionY;
						String posVal=position.replace(",",".");
						double mpKey = Double.parseDouble(posVal);
						
						orderMap.put(mpKey,widgetInfoName);
						
						configureInfo.put("widgetPosition",position);
						configureInfo.put("widgetSize",widgetInfoObj.get("size_x")+","+widgetInfoObj.get("size_y"));
						configureInfo.put("widgetWidth",widgetInfoObj.get("width"));
						configureInfo.put("widgetHeight",widgetInfoObj.get("height"));
						//configureInfo.put("widgetWidth",Integer.parseInt(widgetInfoObj.get("width")+""));
						//configureInfo.put("widgetHeight",Integer.parseInt(widgetInfoObj.get("height")+""));
						// widget*~*info=acbd
						
						congigureVars.add(widgetInfoName);
						congigureVals.add(configureInfo.toString());
						
						displayVals.add(widgetInfoObj.get("headerDescription"));
						//displayVars.add(widgetInfoName+"*~*headerDescription");
						displayVars.add(widgetInfoName+"*$*headerDescription");
						if(widgetInfoObj.get("descDisplayName")!=null)
						{
							displayVals.add(widgetInfoObj.get("descDisplayName"));
							//displayVars.add(widgetInfoName+"*~*info");
							displayVars.add(widgetInfoName+"*$*info");
						}
						if(widgetInfoObj.get("selectedPaletteColor")!=null)
						{
							displayVals.add(widgetInfoObj.get("selectedPaletteColor")); //for custom selected color palette
							//displayVars.add(widgetInfoName+"*~*ColorCode"); //for custom selected color palette
							displayVars.add(widgetInfoName+"*$*ColorCode"); //for custom selected color palette
						}
					}
					if(orderMap.size()>0)
					{
						Set set = orderMap.entrySet();
						Iterator iterator = set.iterator();
						JSONArray orderAry = new JSONArray();
						while(iterator.hasNext()) 
						{
							Map.Entry mentry = (Map.Entry)iterator.next();
							orderAry.add(mentry.getValue().toString());
						}
						congigureVars.add("widgetOrder");
						congigureVals.add(orderAry.toString());
					}
				}
			}
				//System.out.println("[Reporttemplatecontroller]displayVals==>>!  "+displayVals);
				//System.out.println("[Reporttemplatecontroller]congigureVals!  "+congigureVals);
			// delete old data while update template
			if(templateList.contains(templateName))
			{
				iniFile.deleteSubject(templateName+"_overview");
				iniFile.deleteSubject(templateName+"_detailview");
				iniFile.deleteSubject(templateName+"_displayView");
				iniFile.deleteSubject(templateName+"_configureview");
			}
			overVars.add("CreatedBy");
			overVals.add(urs);
			overVars.add("createdDate");
			overVals.add(new SimpleDateFormat ("E yyyy.MM.dd 'at' hh:mm:ss a zzz").format(new Date()));
			if(flag)
				flag=iniFile.setValues(templateName+"_overview", overVars, overVals,false);
			if(flag)
				flag=iniFile.setValues(templateName+"_detailview", detailVars, detailVals,false);
			if(flag)
				flag=iniFile.setValues(templateName+"_configureview", congigureVars, congigureVals,false);
			if(flag)
				flag=iniFile.setValues(templateName+"_displayView", displayVars, displayVals,false);
			if(flag)
				iniFile.saveFile();
			if(flag)
			{
				templateJson.put("status", "success");				
				if(clusterSupported && isSecondaryManager)
				{
					String primaryIP = managersIni.getPrimaryManagerIP();
					String thisManagerIP = managersIni.getManagerIP();
					SMClusterHelper smCluster=new SMClusterHelper(primaryIP,thisManagerIP);
					Vector paramsToPrimaryManager=new Vector();
					paramsToPrimaryManager.add("1~custom_Reports~"+templateName+"~"+templateName+"_overview,"+templateName+"_detailview");
					for(int s=0;s<overVars.size();s++)
					{
						String eachVar=(String)overVars.get(s);
						String eachVal=(String)overVals.get(s);
						paramsToPrimaryManager.add("1~"+templateName+"_overview~"+eachVar+"~"+eachVal);
					}
					for(int s=0;s<detailVars.size();s++)
					{
						String eachVar=(String)detailVars.get(s);
						String eachVal=(String)detailVals.get(s);
						paramsToPrimaryManager.add("1~"+templateName+"_detailview~"+eachVar+"~"+eachVal);
					}
					for(int s=0;s<congigureVars.size();s++)
					{
						String eachVar=(String)congigureVars.get(s);
						String eachVal=(String)congigureVals.get(s);
						paramsToPrimaryManager.add("1~"+templateName+"_configureview~"+eachVar+"~"+eachVal);
					}
					for(int s=0;s<displayVars.size();s++)
					{
						String eachVar=(String)displayVars.get(s);
						String eachVal=(String)displayVals.get(s);
						paramsToPrimaryManager.add("1~"+templateName+"_displayView~"+eachVar+"~"+eachVal);
					}
					boolean uploadSuccess=smCluster.uploadTemplateToPrimaryManager(paramsToPrimaryManager);
				}
			}
			else
			{			
				templateJson.put("status", "failure");
				templateJson.put("msg", errorMsg);
			}
		}
		else if(method.equals("deleteAndGetIni"))
		{		
			Enumeration enames=request.getParameterNames();
			List<TemplateInfoBean> templateInfoBeanList=new ArrayList <TemplateInfoBean>();
			while(enames.hasMoreElements())
			{
				String ename=(String)enames.nextElement();
				if(ename.startsWith("recordInfo"))
				{
					String recordInfo = request.getParameter(ename);
					JSONObject templateInfoObj = (JSONObject) JSONSerializer.toJSON(recordInfo);
					templateInfoBeanList.add((TemplateInfoBean) JSONObject.toBean(templateInfoObj, TemplateInfoBean.class));
				}
			}
			
			IniFile iniFile = new IniFile(EgInstallInfo.getInstallDir()+"/manager/config/"+iniFileName+".ini",true);
			ArrayList templateList =new ArrayList(Arrays.asList(iniFile.getVariables("custom_Reports")));
			
			boolean flag=false;
			for(int i=0;i<templateInfoBeanList.size();i++)
			{
				TemplateInfoBean templateInfoBean =(TemplateInfoBean)templateInfoBeanList.get(i);
//				ReportBuilderBean builderBean=new ReportBuilderBean(sessionId,urs,templateInfoBean.getTemplateName(),permission);
				boolean deleteStatus=reportBean.deleteTemplateFromDb(sessionId,urs,templateInfoBean.getTemplateName());
				if(templateList.contains(templateInfoBean.getTemplateName()))
				{
					templateList.remove(templateInfoBean.getTemplateName());
					String templateDetailsVariable=iniFile.getValue("custom_Reports",templateInfoBean.getTemplateName());
					//StringTokenizer strTokenizer=new StringTokenizer(templateDetailsVariable,",");
					ArrayList strTokenizer=ErUtils.egTokenizer(templateDetailsVariable,",");
					//while(strTokenizer.hasMoreElements())
					for(int j=0;j<strTokenizer.size();j++)
					{
						String str=strTokenizer.get(j).toString();
						iniFile.deleteSubject(str);
					}
					iniFile.deleteSubject(templateInfoBean.getTemplateName()+"_displayView");
					iniFile.deleteSubject(templateInfoBean.getTemplateName()+"_configureview");
					iniFile.deleteValue("custom_Reports",templateInfoBean.getTemplateName());
					flag=true;
					if(clusterSupported && isSecondaryManager)
					{
						String primaryIP = managersIni.getPrimaryManagerIP();
						String thisManagerIP = managersIni.getManagerIP();
						SMClusterHelper smCluster=new SMClusterHelper(primaryIP,thisManagerIP);
						Vector paramsToPrimaryManager=new Vector();
						paramsToPrimaryManager.add("3~"+templateInfoBean.getTemplateName()+"_overview");
						paramsToPrimaryManager.add("3~"+templateInfoBean.getTemplateName()+"_detailview");
						paramsToPrimaryManager.add("3~"+templateInfoBean.getTemplateName()+"_displayView");
						paramsToPrimaryManager.add("3~"+templateInfoBean.getTemplateName()+"_configureview");
						paramsToPrimaryManager.add("2~custom_Reports~"+templateInfoBean.getTemplateName());
						boolean uploadSuccess=smCluster.uploadTemplateToPrimaryManager(paramsToPrimaryManager);
					}
				}
			}
			if(flag)
			{
				iniFile.saveFile();
				templateJson.put("status", "success");
				JSONArray getGridData=getIni(iniFile,reportBean,sessionId,urs,builderType);
				JSONArray listViewData=new JSONArray();
				listViewData=getGridData;
				for(int jk=0;jk<listViewData.size();jk++)
				{
					JSONObject dataObj = (JSONObject)listViewData.get(jk);
					dataObj.put("disbleFlag",true);
					dataObj.put("deleteUrl","");
					dataObj.put("Delete","Delete");
					dataObj.put("EditSettings","Edit Settings");
					dataObj.put("Generate","Generate");
					dataObj.put("templateImg","../images/Dark/listViewWidgetDefault.png");
					
					if((String)dataObj.get("modifiedDate")==null)
						dataObj.put("modifiedDate","");
					if((String)dataObj.get("builderConfigString")==null)
						dataObj.put("builderConfigString","");
					if((String)dataObj.get("disbleStatus")==null)
					{
						dataObj.put("disbleStatus","");
						dataObj.put("disbleFlag",false);
					}
					if((String)dataObj.get("sharedBy")!=null&&((String)dataObj.get("sharedBy")).equalsIgnoreCase("Own"))
					{
						dataObj.put("isShareByOwn",true);
					}else
						dataObj.put("isShareByOwn",false);

					if((String)dataObj.get("sharing")!=null&&((String)dataObj.get("sharing")).equalsIgnoreCase("Private"))
					{
						dataObj.put("isShared",false);
					}else
						dataObj.put("isShared",true);

				}
				templateJson.put("listViewData", listViewData);
				templateJson.put("gridData",getGridData);
			}
			else
			{
				templateJson.put("status", "failure");
				templateJson.put("msg", errorMsg);
			}
		}
		else if(method.equalsIgnoreCase("getUsers")){
			//for getting all users
			ReportBuilderBean reportBuilderBean=new ReportBuilderBean(sessionId,urs);
			JSONArray userArray=reportBuilderBean.getAllUsers();
			JSONArray userTempArray= new JSONArray();
			
			for (int i=0; i < userArray.size(); i++) 
			{
				JSONObject userTempObject = (JSONObject)userArray.get(i);
				String displayField = userTempObject.get("displayField").toString();
				String valueField = userTempObject.get("valueField").toString();
				if((!displayField.equalsIgnoreCase(urs)) || (!valueField.equalsIgnoreCase(urs)))
				{
					userTempArray.add(userTempObject);
				}
			}
			userArray=userTempArray;
			
			templateJson.put("userArray",userArray);
		}
		else if(method.equalsIgnoreCase("getGraphPalettes"))
		{
			IniFile inifile = new IniFile(EgInstallInfo.getInstallDir()+"/manager/config/eg_report.ini");
			JSONObject palettes = new JSONObject();	
			String totalPalette=inifile.getValue("ReportBuilder_Palette","BuilderPalette");
			JSONArray totalPaletteAry=getJSONArrayForTokens(totalPalette,",");
			for(int i=1;i<=totalPaletteAry.size();i++)
			{
				String colorPalette=inifile.getValue("Report_Builder","Palette"+i);
				palettes.put("Palette"+i,getJSONArrayForTokens(colorPalette,","));
			}
			templateJson.put("palettes", palettes);
		}
		else
		{
			request.setAttribute("userId",urs);
			request.setAttribute("sessionId",session.getId());
			ReportTemplateBean templateBean=new ReportTemplateBean(request);	
			templateJson.put("status", "success");
			templateJson.put("combo", templateBean.getCombos());
			templateJson.put("selectedFields", templateBean.getSelectedFields());
			templateJson.put("displayFields", templateBean.getDisplayFields());
			
		}
	}
	else
	{
 		templateJson.put("status", "failure");
		templateJson.put("msg", errorMsg);
	}
	//System.out.println("[ReportTemplateController] response  "+templateJson.toString());
	response.getWriter().write(templateJson.toString());
}
catch (Exception ex)
{
	ex.printStackTrace();
}
%>


<%!
public synchronized List getListForTokens(String str,String delimiter){
	//StringTokenizer strTokenizer=new StringTokenizer(str,delimiter);
	ArrayList strTokenizer=ErUtils.egTokenizer(str, delimiter);
	List lst=new ArrayList();
	//while(strTokenizer.hasMoreElements())
	for(int i=0;i<strTokenizer.size();i++)
	{ 
		lst.add(strTokenizer.get(i).toString());
	}
	return lst;
}
public synchronized JSONArray getJSONArrayForTokens(String str,String delimiter){
	//StringTokenizer strTokenizer=new StringTokenizer(str,delimiter);
	ArrayList strTokenizer=ErUtils.egTokenizer(str, delimiter);
	JSONArray lst=new JSONArray();
	//while(strTokenizer.hasMoreElements())
	for(int i=0;i<strTokenizer.size();i++)
	{ 
		lst.add(strTokenizer.get(i).toString());
	}
	return lst;
}
public synchronized JSONArray getDDConfig(JSONArray ddRawConfigArray,EgMappingInfo intlmap,Map changeFnNames)
{
	//JSONArray ddRawConfigArray=(JSONArray)templateInfoObj.get(ddConfigStr);
	JSONArray rows=new JSONArray();
	for(int j=0;j<ddRawConfigArray.size();j++)
	{
		String ddRawConfigInfoStr=(String)ddRawConfigArray.get(j);
		int index=ddRawConfigInfoStr.indexOf("=");
		String componentType=ddRawConfigInfoStr.substring(0,index);
		ddRawConfigInfoStr=ddRawConfigInfoStr.substring(index+1);

		List ddRawConfigInfoList=getListForTokens(ddRawConfigInfoStr,"|");

		String test=(String)ddRawConfigInfoList.get(0);
		String testValue=(String)ddRawConfigInfoList.get(0);
		String er_testType="Measures";
		if(test.endsWith("_DDD"))
		{
			er_testType="Details";
			test=test.substring(0,test.indexOf("_DDD"));
		}
		String measure=(String)ddRawConfigInfoList.get(1);
		String displayName=null;		
		String glduration=null;		
		String er_duration=null;		
		//int ms=0;
		//StringTokenizer token=new StringTokenizer(measure, "$~$");
		ArrayList token=ErUtils.egTokenizer(measure, "$~$");
		/*while(token.hasMoreTokens())
		{
			String mesStr=token.nextToken();
			if(ms<=1)
			{
				displayName=mesStr;
			}	
			if(ms==0)
				measure=mesStr;
			if(ms==2)
				glduration=mesStr;
			if(ms==3)
				er_duration=mesStr;
			ms++;
		}*/
		for(int ms=0;ms<token.size();ms++)
		{
			String mesStr=(String)token.get(ms);
			if(ms<=1)
			{
				displayName=mesStr;
			}	
			if(ms==0)
				measure=mesStr;
			if(ms==2)
				glduration=mesStr;
			if(ms==3)
				er_duration=mesStr;
		}

		String infos=(String)ddRawConfigInfoList.get(2);
		if(infos!=null && infos.equals("-1")){
			infos="-";
		}
		String function=(String)ddRawConfigInfoList.get(3); 
		String configString=null;
		if(function!=null && function.equals("Raw"))
		{
			configString=componentType+"="+ddRawConfigInfoStr;
		}
		else
		{
			configString="comptypeid"+componentType+"="+ddRawConfigInfoStr;
		}
		if(changeFnNames.get(function)!=null)
		{
			function=(String)changeFnNames.get(function);
		}
		
		JSONObject row=new JSONObject();
		row.put("componentType",intlmap.getComponentTypeDescription(componentType));
		row.put("test",intlmap.getTestDescription(test));
		row.put("measure",intlmap.getMeasureDescription(test,measure));
		row.put("displayName",intlmap.getMeasureDescription(test,displayName));
		row.put("displayNameDummy",displayName.substring(0,displayName.indexOf("(")));
		row.put("measureValue",measure);
		row.put("testValue",testValue);
		row.put("descriptor",infos);
		row.put("er_testType",er_testType);
		row.put("function",function);
		row.put("configString",configString);
		row.put("glduration",glduration);
		row.put("er_duration",er_duration);
		rows.add(row);
	}
	return rows;
}
public synchronized JSONArray getConfig(String configStr,String componentType,EgMappingInfo intlmap,Map changeFnNames,ArrayList removableMesList,JSONObject ddGroupByMeasure)
{
	//System.out.println("======configStr==========>>>>>>>..>>>>>>>"+configStr);
	JSONArray rows=new JSONArray();
	List componentTypeInfosList=getListForTokens(configStr,"*");
	for(int j=0;j<componentTypeInfosList.size();j++)
	{
		String componentTypeInfo=(String)componentTypeInfosList.get(j);
		List componentTypeInfoList=getListForTokens(componentTypeInfo,"|");
		if(removableMesList.contains(componentTypeInfo))
		{
			continue;
		}

		String test=(String)componentTypeInfoList.get(0);
		String testValue=(String)componentTypeInfoList.get(0);
		String er_testType="Measures";
		boolean ddTest=false;
		if(test.endsWith("_DDD"))
		{
			er_testType="Details";
			test=test.substring(0,test.indexOf("_DDD"));
			ddTest=true;
		}
		String measure=(String)componentTypeInfoList.get(1);
		String displayName=null;
		String glduration=null;
		String er_duration=null;
		/*int ms=0;
		StringTokenizer token=new StringTokenizer(measure, "$~$");
		while(token.hasMoreTokens())
		{
			String mesStr=token.nextToken();
			if(ms<=1)
			{
				displayName=mesStr;
			}	
			if(ms==0)
				measure=mesStr;	
			if(ms==2)
				glduration=mesStr;
			if(ms==3)
				er_duration=mesStr;
			ms++;
		}*/
		ArrayList token=ErUtils.egTokenizer(measure, "$~$");
		String ddColumn=null;
		for(int ms=0;ms<token.size();ms++)
		{
			String mesStr=(String)token.get(ms);
			if(ms<=1)
			{
				displayName=mesStr;
			}	
			if(ms==0)
			{
				measure=mesStr;
				if(ddTest && measure.indexOf("~")!= -1)
				{
					//ddColumn=measure.substring(measure.indexOf("~")+1);
					//measure=measure.substring(0,measure.indexOf("~"));
					ddColumn=measure.substring(0,measure.lastIndexOf("~"));
					if(ddColumn != null && ddColumn.indexOf("~") != -1)
						ddColumn=ddColumn.substring(ddColumn.indexOf("~")+1);
					measure=measure.substring(measure.lastIndexOf("~")+1);		
				}
			}
			if(ms==2)
				glduration=mesStr;
			if(ms==3)
				er_duration=mesStr;
		}
		String infos=(String)componentTypeInfoList.get(2);
		if(infos!=null && infos.equals("-1")){
			infos="-";
		}
		String function=(String)componentTypeInfoList.get(3); 
		//System.out.println("function 1 "+function);
		String configString="comptypeid"+componentType+"="+componentTypeInfo;
		
		if(changeFnNames.get(function)!=null)
		{
			function=(String)changeFnNames.get(function);
		}
		//System.out.println("function 1 "+function);
		JSONObject row=new JSONObject();
		String displayMesDes=intlmap.getMeasureDescription(test,displayName);
		row.put("displayName",displayMesDes);
		row.put("displayNameDummy",displayName.substring(0,displayName.indexOf("(")));
		row.put("componentType",intlmap.getComponentTypeDescription(componentType));
		row.put("test",intlmap.getTestDescription(test));
		row.put("measure",intlmap.getMeasureDescription(test,measure));
		row.put("measureValue",measure);
		if(ddColumn != null)
		{
			row.put("ddColumn",intlmap.getMeasureDescription(test,ddColumn));
			row.put("ddColumnValue",ddColumn);
		}
		row.put("er_testType",er_testType);
		row.put("testValue",testValue);
		//row.put("displayName",intlmap.getMeasureDescription(test,displayName));
		row.put("descriptor",infos);
		row.put("function",function);
		row.put("configString",configString);
		row.put("glduration",glduration);
		row.put("er_duration",er_duration);
		if(ddGroupByMeasure==null||ddGroupByMeasure.get(displayMesDes)==null)
			row.put("ddconfigString","");
		else{
			String ddconfigString="";
			JSONArray ddMesConfigStrArry = (JSONArray)ddGroupByMeasure.get(displayMesDes);
			for(int ii=0;ii<ddMesConfigStrArry.size();ii++)
			{
				String tempConfigStr=(String)ddMesConfigStrArry.get(ii);
				ddconfigString=ddconfigString+"comptypeid"+tempConfigStr;
				if(ii<ddMesConfigStrArry.size()-1)
				{
					ddconfigString=ddconfigString+"*";
				}
			//	removableMesList.add(tempStr);
			}
					row.put("ddconfigString",ddconfigString);
		}
rows.add(row);
	}
	return rows;
}

public synchronized JSONArray getTotalMes(String configStr,String componentType,EgMappingInfo intlmap,Map changeFnNames,ArrayList removableMesList,JSONObject ddGroupByMeasure, JSONObject widgetObj,String infoLabel,InfoHandler infoHandler)
{
	
	JSONArray rows=new JSONArray();
	List componentTypeInfosList=getListForTokens(configStr,"*");
	//System.out.println("componentTypeInfosList________"+componentTypeInfosList);
	for(int j=0;j<componentTypeInfosList.size();j++)
	{

		String componentTypeInfo=(String)componentTypeInfosList.get(j);
		List componentTypeInfoList=getListForTokens(componentTypeInfo,"|");
		if(removableMesList.contains(componentTypeInfo))
		{
			continue;
		}

		JSONObject comboObj = new JSONObject();
		JSONObject selectedFieldObj = new JSONObject();

		String test=(String)componentTypeInfoList.get(0);
		String testValue=(String)componentTypeInfoList.get(0);
		String er_testType="Measures";
		boolean ddTest=false;
		if(test.endsWith("_DDD"))
		{
			er_testType="Details";
			test=test.substring(0,test.indexOf("_DDD"));
			ddTest=true;
		}
		String measure=(String)componentTypeInfoList.get(1);
		String displayName=null;
		String glduration=null;
		String er_duration=null;

		String ddColumn=null;
		ArrayList token=ErUtils.egTokenizer(measure, "$~$");
		for(int ms=0;ms<token.size();ms++)
		{
			String mesStr=(String)token.get(ms);
			if(ms<=1)
			{
				displayName=mesStr;
			}	
			if(ms==0)
			{
				measure=mesStr;
				if(ddTest && measure.indexOf("~")!= -1)
				{
					ddColumn=measure.substring(measure.lastIndexOf("~")+1);
					measure=measure.substring(0,measure.indexOf("~"));		
				}
			}
			if(ms==2)
				glduration=mesStr;
			if(ms==3)
				er_duration=mesStr;
		}
		String infos=(String)componentTypeInfoList.get(2);
		if(infos!=null && infos.equals("-1")){
			infos="-";
		}
		String function=(String)componentTypeInfoList.get(3); 
		//System.out.println("function 2 "+function);
		String configString="comptypeid"+componentType+"="+componentTypeInfo;
		
		if(changeFnNames.get(function)!=null)
		{
			function=(String)changeFnNames.get(function);
		}
		//System.out.println("function 2 "+function);
		JSONObject row=new JSONObject();
		String displayMesDes=intlmap.getMeasureDescription(test,displayName);

		JSONArray comboDataAry = new JSONArray();
		JSONObject comboData = new JSONObject();
		comboData.put("displayField",intlmap.getComponentTypeDescription(componentType));
		comboData.put("valueField",componentType);
		comboDataAry.add(comboData);
		comboObj.put("componentTypeCombo", comboDataAry);
		selectedFieldObj.put("selectedComponentTypeCombo",componentType);

		comboDataAry = new JSONArray();
		comboData = new JSONObject();
		comboData.put("displayField",intlmap.getTestDescription(test));
		comboData.put("valueField",testValue);
		comboDataAry.add(comboData);
		comboObj.put("testCombo",comboDataAry);
		selectedFieldObj.put("selectedTestCombo",testValue);

		comboDataAry = new JSONArray();
		comboData = new JSONObject();
		String unit=infoHandler.getEgTablesInfo().getUnitForMeasure(test,measure);//..
		comboData.put("displayField", intlmap.getMeasureDescription(test,measure)+" ("+unit+")");
		comboData.put("valueField", measure);
		comboDataAry.add(comboData);
		comboObj.put("measureCombo",comboDataAry);
		selectedFieldObj.put("selectedMeasureCombo",measure);

		if(ddColumn != null)
		{
			comboDataAry = new JSONArray();
			comboData = new JSONObject();
			comboData.put("displayField", intlmap.getMeasureDescription(test,ddColumn));
			comboData.put("valueField", ddColumn);
			comboDataAry.add(comboData);
			comboObj.put("ddColumnCombo",comboDataAry);
			selectedFieldObj.put("selectedDDcolumnCombo",ddColumn);
		}

		comboDataAry = new JSONArray();
		comboData = new JSONObject();
		comboData.put("displayField",function);
		if(function.equalsIgnoreCase("No Calculation"))
		{
			comboData.put("valueField","Raw");
		}
		else if (function.equalsIgnoreCase("Latest Data"))
		{
			comboData.put("valueField","Current");
		}
		else
			comboData.put("valueField",function);
		
		comboDataAry.add(comboData);
		comboObj.put("functionCombo", comboDataAry);
		selectedFieldObj.put("selectedFunctionCombo", comboData.get("valueField"));

		JSONArray ddGroupAry = (JSONArray)ddGroupByMeasure.get(displayMesDes);
		String fieldValues = "";
		String disValue = "";
		if(ddGroupAry!=null && ddGroupAry.size()>0)
		{
			for(int v = 0;v<ddGroupAry.size();v++)
			{
				String ddStr = (String)ddGroupAry.get(v);
				ddStr = ddStr.substring(ddStr.indexOf("|")+1,ddStr.indexOf("$"));
				String ddStrDisp=intlmap.getMeasureDescription(test,ddStr);			
				if(ddTest)
					ddStrDisp=ddStr;
				//String ddStrDisp = intlmap.getTestDescription(ddStr);
				fieldValues = fieldValues+ddStr+",";
				disValue = disValue+ddStrDisp+",";
			}
			fieldValues = fieldValues.substring(0,fieldValues.length()-1);
			disValue = disValue.substring(0,disValue.length()-1);
		}

		selectedFieldObj.put("ddGroupInfoTxtValue",disValue);
		selectedFieldObj.put("ddGroupInfoTxtFieldValues",fieldValues);
		//Available memory   (Max)$spark$A2CD3A$iconChartTypeArea$iconFontMedium
		if(displayName != null)
		{
			if(displayName.indexOf("@") != -1)
			{
				String digitalIcon=displayName.substring(displayName.indexOf("@")+1);
				if(digitalIcon.indexOf("$spark$")!=-1)
					digitalIcon=digitalIcon.substring(0,digitalIcon.indexOf("$spark$"));
				selectedFieldObj.put("digitalIcon",digitalIcon);
			}
			if(displayName.indexOf("$spark$") != -1)
			{
				String tempDispName=displayName.substring(displayName.indexOf("$spark$")+"$spark$".length());
				ArrayList sparkDetail=ErUtils.egTokenizer(tempDispName, "$");
				for(int s=0;s<sparkDetail.size();s++)
				{
					String eachData=(String)sparkDetail.get(s);
					if(s==0)
						selectedFieldObj.put("sparkColor",eachData);
					else if(s==1)
						selectedFieldObj.put("sparkType",eachData);
					else if(s==2)
						selectedFieldObj.put("sparkFont",eachData);
				}
			}
			if(displayName.indexOf("$MeasCon$") != -1)
			{
				String tempDispName=displayName.substring(displayName.indexOf("$MeasCon$")+"$MeasCon$".length());
				ArrayList measureDetail=ErUtils.egTokenizer(tempDispName, "$");
				for(int s=0;s<measureDetail.size();s++)
				{
					String eachData=(String)measureDetail.get(s);
					if(s==0)
						selectedFieldObj.put("selectedMeasureCondtion",eachData);
					else if(s==1)
						selectedFieldObj.put("selectedMeasureCritical",eachData);
					else if(s==2)
						selectedFieldObj.put("selectedMeasureMajor",eachData);
					else if(s==3)
						selectedFieldObj.put("selectedMeasureMinor",eachData);
				}
			}
		}
		selectedFieldObj.put("selectedDispMeasureCombo",displayName.substring(0,displayName.indexOf("(")));
		selectedFieldObj.put("selectedYaxis",widgetObj.get("yAxisLabel"));
		JSONArray grpAry = (JSONArray)widgetObj.get("groupBy");
		comboObj.put("groupByCombo",grpAry);

		comboDataAry = new JSONArray();
		comboData = new JSONObject();
		
		if(glduration.indexOf("dynamic")>-1)
		{
			selectedFieldObj.put("selectedDynamic",true);
			glduration = glduration.replace("dynamic","");
		}
		else
			selectedFieldObj.put("selectedDynamic",false);

		if(glduration.equalsIgnoreCase("None"))
			comboData.put("displayField","None");
		else if(glduration.equalsIgnoreCase("gt"))
			comboData.put("displayField","Greater than");
		else if(glduration.equalsIgnoreCase("ge"))
			comboData.put("displayField","Greater than or equals");
		else if(glduration.equalsIgnoreCase("eq"))
			comboData.put("displayField","Equals");
		else if(glduration.equalsIgnoreCase("lt"))
			comboData.put("displayField","Lesser than");
		else if(glduration.equalsIgnoreCase("le"))
			comboData.put("displayField","Lesser than or equals");
		else if(glduration.equalsIgnoreCase("cnt"))
			comboData.put("displayField","Contains");
		else if(glduration.equalsIgnoreCase("like"))
			comboData.put("displayField","Like");
		
		comboData.put("valueField",glduration);
		comboDataAry.add(comboData);
		comboObj.put("gldurationCombo",comboDataAry);
		selectedFieldObj.put("selectedglduration",glduration);
		selectedFieldObj.put("selectedDuration",er_duration);

		comboDataAry = new JSONArray();
		comboData = new JSONObject();
		if(infos.equals("-"))
		{
			comboData.put("displayField","All Descriptors");
			comboData.put("valueField","all");
			selectedFieldObj.put("selectedThresholds","all");
		}
		else
		{
			comboData.put("displayField","Specific Descriptors");
			comboData.put("valueField","specific");
			selectedFieldObj.put("selectedThresholds","specific");
		}
			
		comboDataAry.add(comboData);
		comboObj.put("descFilterCombo",comboDataAry);
		selectedFieldObj.put("selectedActionOnDes","include");
		if(infos.indexOf("$")>-1)
		{
			infos = infos.replaceAll("\\$",",");
		}
		if(infos.indexOf(",exclude")>-1)
		{
			infos = infos.replaceAll(",exclude","");
			selectedFieldObj.put("selectedActionOnDes","exclude");
		}
		selectedFieldObj.put("selecteddescriptorTxt",infos);

		if(grpAry.contains("descriptors"))
		{
			selectedFieldObj.put("selectedDescriptorTxtField",infoLabel);
			selectedFieldObj.put("selectedDescFilterEnable",false);
		}

		String topVal = (String)widgetObj.get("enableTopN");
		if(topVal.equalsIgnoreCase("yes"))
		{
			comboDataAry = new JSONArray();
			comboData = new JSONObject();
			comboData.put("displayField",widgetObj.get("top"));
			comboData.put("valueField",widgetObj.get("top"));
			comboDataAry.add(comboData);
			comboObj.put("topNCombo", comboDataAry);
			selectedFieldObj.put("selectedTopN",widgetObj.get("top")); 
		}
		selectedFieldObj.put("selectedEnableTopN",topVal);

		row.put("combo",comboObj);
		row.put("selectedFields",selectedFieldObj);
		rows.add(row);
	}
	return rows;
}


public synchronized JSONObject getDummyGraphData()
{
	JSONObject dummyGraphObj = new JSONObject();
	EgReportInfo reportInfo = new EgReportInfo("manager");	
	String chartTypeStr = reportInfo.getValue("ReportBuilder_Preview", "chartType");
	String chartTypeAry[] = chartTypeStr.split(",");

	for(int i=0;i<chartTypeAry.length;i++)
	{
		
		String chartJson = reportInfo.getValue("ReportBuilder_Preview", chartTypeAry[i]);
		JSONObject templateInfoBeanObj = (JSONObject) JSONSerializer.toJSON(chartJson);
		if(chartTypeAry[i]!=null && chartTypeAry[i].equalsIgnoreCase("timeline"))
		{
			templateInfoBeanObj.put("setSpacingReportTemplate","true");
		}
		dummyGraphObj.put(chartTypeAry[i],templateInfoBeanObj);
	}
	
	if(true)
		return dummyGraphObj;


	JSONObject graphObj = new JSONObject();
	JSONArray dataSetAry = new JSONArray();
	JSONArray xAxisLabel = new JSONArray();
	
	JSONObject dataSetObj = new JSONObject();
	JSONArray dataAry = new JSONArray();
	JSONObject dataObj = new JSONObject();
	dataObj.put("y",125);
	dataAry.add(dataObj);
	dataObj = new JSONObject();
	dataObj.put("y",100);
	dataAry.add(dataObj);
	dataSetObj.put("data",dataAry);
	dataSetObj.put("color","#8399b0");
	dataSetObj.put("name","Measure-1");
	dataSetAry.add(dataSetObj);

	dataSetObj = new JSONObject();
	dataAry = new JSONArray();
	dataObj = new JSONObject();
	dataObj.put("y",75);
	dataAry.add(dataObj);
	dataObj = new JSONObject();
	dataObj.put("y",50);
	dataAry.add(dataObj);
	dataSetObj.put("data",dataAry);
	dataSetObj.put("color","#ffd95a");
	dataSetObj.put("name","Measure-2");
	dataSetAry.add(dataSetObj);

	xAxisLabel.add("Compnent-1");
	xAxisLabel.add("Compnent-2");
	
	graphObj.put("barAlignment","Horizontal");
	graphObj.put("centerlegendPostion","true");
	graphObj.put("chartFor","bar");
	graphObj.put("chartHeight","240");
	graphObj.put("chartType","bar");
	graphObj.put("chartWidth","295");
	graphObj.put("disableStacking",true);
	graphObj.put("displaynameInTlTip",true);
	graphObj.put("inside",false);
	graphObj.put("isDataLabelEnabled",false);
	graphObj.put("LabelsCount",2);
	graphObj.put("legend","true");
	graphObj.put("legendPosition","center");
	graphObj.put("rawMuliCompTitle","");
	graphObj.put("title","UNTITLED");
	graphObj.put("xAxisLabelText","Component");
	graphObj.put("yAxisLabel","");
	graphObj.put("xAxisLabel",xAxisLabel);
	graphObj.put("DataSet",dataSetAry);
	dummyGraphObj.put("bar",graphObj);

	graphObj = new JSONObject();

	graphObj.put("chartTitle","");
	graphObj.put("chartHeight","240");
	graphObj.put("chartWidth","295");
	graphObj.put("lowerLimit","1494822600000");
	graphObj.put("higherLimit","1494840600000");
	graphObj.put("isDDEnabled","no");
	graphObj.put("legend","false");
	graphObj.put("LegendPosition","top");
	graphObj.put("LineWidth","2");
	graphObj.put("showdisconnectedline","Yes");
	graphObj.put("showLegendsEnable","false");
	graphObj.put("TimeFormatOut","HH:mm");
	graphObj.put("timeScale","30");
	graphObj.put("title","");
	graphObj.put("yAxisLabelYval","28");
	graphObj.put("yLabel","MB");
	graphObj.put("DataSet",this.getAreaDataSet());
	dummyGraphObj.put("timeline",graphObj);

	return dummyGraphObj;
}
public synchronized JSONArray getAreaDataSet()
{
	JSONArray dataSetAry = new JSONArray();
	ArrayList timeList = new ArrayList();
	ArrayList<Integer> dataList = new ArrayList<Integer>();

	timeList.add("1494822600000");
	dataList.add(294);
	timeList.add("1494826200000");
	dataList.add(694);
	timeList.add("1494829800000");
	dataList.add(661);
	timeList.add("1494833400000");
	dataList.add(670);
	timeList.add("1494837000000");
	dataList.add(102);
	timeList.add("1494840600000");
	dataList.add(504);

	JSONObject dataSetObj = new JSONObject();
	dataSetObj.put("name","Measure - 1");
	dataSetObj.put("color","#8399b0");
	JSONArray dataAry = new JSONArray();
	for(int i=0 ; i<dataList.size();i++)
	{
		JSONArray dataInfoAry = new JSONArray();
		dataInfoAry.add(new Long((String)timeList.get(i)));
		dataInfoAry.add(dataList.get(i));
		dataAry.add(dataInfoAry);
	}
	dataSetObj.put("data",dataAry);
	dataSetAry.add(dataSetObj);
	dataSetObj = new JSONObject();
	dataSetObj.put("name","Measure - 2");
	dataSetObj.put("color","#ffd95a");
	dataAry = new JSONArray();
	for(int i=0 ; i<dataList.size();i++)
	{
		JSONArray dataInfoAry = new JSONArray();
		dataInfoAry.add(new Long((String)timeList.get(i)));
		dataInfoAry.add(dataList.get(i)+50);
		dataAry.add(dataInfoAry);
	}
	dataSetObj.put("data",dataAry);
	dataSetAry.add(dataSetObj);

	return dataSetAry;
}
public synchronized JSONArray getIni(IniFile iniFile,ReportBuilderBean reportBean,String sessionId,String urs,String builderType)
{
	JSONArray gridArr=new JSONArray();
	try{
		List dbTemplateList = reportBean.getTemplateFromDb(sessionId,urs);
		List favSchList=new ArrayList();
		List favSchTemplateList=reportBean.getFavRecordInfoFromDb();
		
		for(int i=0;i<favSchTemplateList.size();i++){
			JSONObject templateInfoBeanObj = (JSONObject) JSONSerializer.toJSON((String)favSchTemplateList.get(i));
			TemplateInfoBean templateInfoBean=(TemplateInfoBean) JSONObject.toBean(templateInfoBeanObj, TemplateInfoBean.class);
			if(!favSchList.contains(templateInfoBean.getTemplateName()))
				favSchList.add(templateInfoBean.getTemplateName());
		}
		
		favSchTemplateList=reportBean.getSchedRecordInfoFromDb();
		
		for(int i=0;i<favSchTemplateList.size();i++){
			JSONObject templateInfoBeanObj = (JSONObject) JSONSerializer.toJSON((String)favSchTemplateList.get(i));
			TemplateInfoBean templateInfoBean=(TemplateInfoBean) JSONObject.toBean(templateInfoBeanObj, TemplateInfoBean.class);
			if(!favSchList.contains(templateInfoBean.getTemplateName()))
				favSchList.add(templateInfoBean.getTemplateName());
		}
		
		ArrayList reportVariablesList =new ArrayList(Arrays.asList(iniFile.getVariables("custom_Reports")));
		//System.out.println("=====favSchList========>>>>>>>>>"+favSchList);
		for(int i=0;i<reportVariablesList.size();i++)
		{
			String reportVariableName=(String)reportVariablesList.get(i);
			if(dbTemplateList.contains(reportVariableName))
			{
				JSONObject obj=new JSONObject();
				obj.put("templateName",reportVariableName);
				String templateNameDisp = reportVariableName;
				if(templateNameDisp.indexOf(".")>-1)
				{
					templateNameDisp = templateNameDisp.substring(templateNameDisp.lastIndexOf(".")+1);
				}
				obj.put("templateNameDisp",templateNameDisp);
				if(favSchList!=null && !favSchList.isEmpty() && favSchList.contains(reportVariableName)){
					obj.put("disbleStatus","true");
				}		
				
				
				String reportVariableValue=iniFile.getValue("custom_Reports",reportVariableName);
				//StringTokenizer reportVariableValueToken = new StringTokenizer(reportVariableValue,",");
				ArrayList reportVariableValueToken=ErUtils.egTokenizer(reportVariableValue,",");
				//if (reportVariableValueToken.hasMoreTokens()){
				if (reportVariableValueToken.size() > 0){
					//String subjectName=reportVariableValueToken.nextToken();
					String subjectName=(String)reportVariableValueToken.get(0);
					
					boolean ownReport=false;
					String sharingValue=iniFile.getValue(subjectName,"sharing");
					String createdBy=iniFile.getValue(subjectName,"CreatedBy");
					if(urs.equals(createdBy))
						ownReport=true;
					if(!ownReport)
					{
						obj.put("disableModifyDelete","true");
						if(builderType==null || (builderType!=null && !builderType.equalsIgnoreCase("generate")))
							continue;
					}
					else
					{
						obj.put("disableModifyDelete","false");
					}
					
					boolean enableReport=true;
					//System.out.println("===builderType===>>>>>>dsf>"+builderType);
						//System.out.println("===ownReport===>>>>>>dsf>"+ownReport);
					if(builderType!=null && builderType.equalsIgnoreCase("create") && !ownReport)
						enableReport=false;
					//System.out.println("=enableReport======>>>>>>"+enableReport);
					if(enableReport)
					{
						if(urs.equals(createdBy))
							obj.put("sharedBy","Own");
						else if(!sharingValue.equalsIgnoreCase("private"))
							obj.put("sharedBy",createdBy);					
						
						ArrayList variablesList =new ArrayList(Arrays.asList(iniFile.getVariables(subjectName)));
						for(int j=0;j<variablesList.size();j++)
						{
							String variableName=(String)variablesList.get(j);
							if(variableName.equals("templateDescription") || variableName.equals("createdDate") || variableName.equals("templateTitle") || variableName.equals("sharing") || variableName.equals("CreatedBy"))
							{						
								String variableValue=iniFile.getValue(subjectName,variableName);
								
								if(variableName.equals("createdDate")){
									try{
										DateFormat formatter = new SimpleDateFormat("E yyyy.MM.dd 'at' hh:mm:ss a zzz");
										Date convertedDate = (Date) formatter.parse(variableValue);
										//System.out.println("[ReportTemplateController before] "+variableValue);
										DateFormat newFormatter = new SimpleDateFormat("MMM dd, yyyy hh:mm a");
										variableValue = newFormatter.format(convertedDate);
										//System.out.println("[ReportTemplateController after] "+variableValue);
									}
									catch(Exception e)
									{
										e.printStackTrace();
									}
								}
								obj.put(variableName,variableValue);
							}
						}
						//System.out.println("=obj======>>>>>>"+obj);
						gridArr.add(obj);
					}
				}
			}
		}
	}catch(Exception tt)
	{
		
	}
	//System.out.println("=======gridArr=======>>>>"+gridArr);
	return gridArr;
}

%>