package com.insx.isomorphic.ds;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.XMLOutputter;

//import org.w3c.dom.*;

import com.isomorphic.rpc.RPCManager;
import com.isomorphic.rpc.ClientMustResubmitException;
import com.isomorphic.datasource.DSRequest;
import com.isomorphic.datasource.DataSource;
import com.isomorphic.datasource.DSResponse;
import com.isomorphic.datasource.DynamicDSGenerator;
import com.isomorphic.datasource.BasicDataSource;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import com.ins.base.InsBase;
import com.insx.isomorphic.ds.AdvancedSearchController;
import com.ins.base.InsResourceMgr;
import java.math.BigDecimal;
import java.util.Map;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Vector;
import java.util.Enumeration;
import java.text.Format;
import java.text.SimpleDateFormat;
import com.insx.ia.iabasics.IADataSetSubscription;
import com.insx.ia.iabasics.IACompanyCache;
import com.insx.ia.iabasics.IACompany;
import com.insx.ia.iabasics.IADemographicData;
import com.insx.ia.iabasics.IADemographicCache;
import com.insx.ia.iabasics.InsTblRptHdr;
import com.insx.ia.iabasics.InsTblRptRow;
import com.insx.ia.iabasics.IAFilingPeriod;
import com.insx.modules.screening.fullSearch.FSResult;
import com.insx.modules.pti.fullSearch.PTIFSResult;
import com.insx.isomorphic.ds.UserSession;
import com.insx.ui.ia.companySelection.IAActiveEntitySet;


//public class FSReportDS extends InsBase implements DynamicDSGenerator{

public class FSReportDS  extends BasicDataSource{

	static XMLOutputter _xmlOutputter = new XMLOutputter();
	
	static{
		 _xmlOutputter.setNewlines(false);
	     _xmlOutputter.setIndent(false);
	}

	public FSReportDS() {
		super();
	};

	public DataSource getDataSource(String prefix, HttpServletRequest request){
		System.out.println("xxxxxxxxxxx get datasource xxxxx");
		String doc = getXMLContents(prefix, request);
		try{
			DataSource ds = DataSource.fromXML(doc);
			return ds;
		}catch (Exception e){
			InsResourceMgr.getDefaultLog().logError(e);
			return null;
		}
	}

    static public String getXMLContents(String prefix, HttpServletRequest request){
		Element ds = new Element("DataSource");
		Document doc = new Document(ds);
		ds.setAttribute("ID", prefix);
		ds.setAttribute("titleField", "description");
		ds.setAttribute("serverType", "generic");
		ds.setAttribute("dataFormat", "iscServer");

		Element so = new Element("serverObject"); 
        so.setAttribute("lookupStyle", "new");
        so.setAttribute("className", "com.insx.isomorphic.ds.FSReportDS");
		ds.addContent(so);

		Element obs = new Element("operationBindings"); 
		ds.addContent(obs);

		Element b = new Element("binding"); 
        b.setAttribute("operationType", "fetchData");
        b.setAttribute("serverMethod", "fetchData");
        b.setAttribute("methodArguments", "$request,$dsRequest");
		obs.addContent(b);

		Element w = new Element("whereClause"); 
        w.addContent("subproduct_id = $subproduct_id");
		b.addContent(w);

		Element fields = new Element("fields");
		ds.addContent(fields);

		try {
			Map requestData = new HashMap<String, Object>();//dsRequest.getCriteria();
			UserSession us = UserSession.getUserSession(request, null, requestData);
			String cmd = (String) requestData.get("cmd");

			Vector hdrs = null;


			if (us.getSubproductID() == IADemographicCache.PTISubproductID) {
			    PTIFSResult ptiRpt = null;
				ptiRpt = us.getFSSession().getPTISearchResult(request);
				hdrs = ptiRpt.getHeaders().getList();

			} else {
			    FSResult rpt = null;
				rpt = us.getFSSession().getSearchResult();
				hdrs = rpt.getHeaders().getList();
			}

			InsTblRptHdr hdr = null;
			HashMap m = null;
			Element fld = null;
			if (hdrs != null) {
				int i = 0;
				for (Enumeration e = hdrs.elements(); e.hasMoreElements();) {
					hdr = (InsTblRptHdr) e.nextElement();
					fld = new Element("field");
					fld.setAttribute("title", hdr.getName());
					fld.setAttribute("name", "c"+i);
					if (hdr.getContentType() == InsTblRptHdr.StringContent)
						fld.setAttribute("type", "text");
					else if (hdr.getContentType() == InsTblRptHdr.IntegerContent) {
						fld.setAttribute("type", "integer");
						fld.setAttribute("formatCellValue",	"isc.Format.toUSString(value)");
					} else if (hdr.getContentType() == InsTblRptHdr.DoubleContent) {
						fld.setAttribute("type", "float");
						fld.setAttribute("formatCellValue",	"isc.Format.toUSString(value)");

					} else if (hdr.getContentType() == InsTblRptHdr.DateContent)
						fld.setAttribute("type", "date");
					else if (hdr.getContentType() == InsTblRptHdr.ClobContent)
						fld.setAttribute("type", "text");
					fields.addContent(fld);
					i++;
				}

				fld = new Element("field");
				fld.setAttribute("type", "text");
				fld.setAttribute("name", "company_code");
				fld.setAttribute("hidden", "true");
				fields.addContent(fld);

				fld = new Element("field");
				fld.setAttribute("type", "text");
				fld.setAttribute("name", "company_code_dis");
				fld.setAttribute("hidden", "true");
				fields.addContent(fld);

				fld = new Element("field");
				fld.setAttribute("type", "text");
				fld.setAttribute("name", "group_code");
				fld.setAttribute("hidden", "true");
				fields.addContent(fld);

				fld = new Element("field");
				fld.setAttribute("type", "text");
				fld.setAttribute("name", "ins_type");
				fld.setAttribute("hidden", "true");
				fields.addContent(fld);
			}
		} catch (Exception e) {
			InsResourceMgr.getDefaultLog().logError(e);
		}
		
		return  _xmlOutputter.outputString(doc);

	}

    public DSResponse fetchData(DSRequest req) throws Exception {
		return fetch(req.getHttpServletRequest(), req);
	}

    public DSResponse fetch(DSRequest req) throws Exception {
		return fetch(req.getHttpServletRequest(), req);
	}

    public DSResponse executeFetch(DSRequest req) throws Exception {
		return fetch(req.getHttpServletRequest(), req);
	}

	public DSResponse fetchData(HttpServletRequest req, DSRequest dsRequest)
			throws Exception {
		return fetch(req, dsRequest);
	}

	public DSResponse fetch(HttpServletRequest request, DSRequest dsRequest)
			throws Exception {

		InsResourceMgr.getDefaultLog().logInfo("xxxxxxxxxxxxxxx FSReportDS:fetch");
		RPCManager rpc;

		DSResponse dsResponse = new DSResponse();
		ArrayList<HashMap<String, Object>>  rows = null;
		Vector retHdrs = new Vector();
		try {
			Map requestData = dsRequest.getCriteria();
			UserSession us = UserSession.getUserSession(request, null, requestData);
			String cmd = (String) requestData.get("cmd");

			Vector hdrs = null;
			Object[] data = null;

			PTIFSResult ptiRpt = null;
			FSResult rpt = null;
			if (us.getSubproductID() == IADemographicCache.PTISubproductID) {
				ptiRpt = us.getFSSession().getPTISearchResult(request);
				hdrs = ptiRpt.getHeaders().getList();
				data = ptiRpt.getData();
			} else {
				rpt = us.getFSSession().getSearchResult();
				hdrs = rpt.getHeaders().getList();
				data = rpt.getData();
			}

			rows = new ArrayList<HashMap<String, Object>>();
			InsTblRptHdr hdr = null;
			HashMap m = null;

			/*
			 * ArrayList formats = null; if(data != null && data.length>0){
			 * formats=rpt.getHeaders().getFormats(); }
			 */
			Format dpFormat = null;
			Object dp = null;
			String disStr = null;
			SimpleDateFormat dateFormat = InsTblRptHdr.dateFormat;
			if (rpt != null || ptiRpt != null) {
				for (Enumeration e = hdrs.elements(); e.hasMoreElements();) {
					hdr = (InsTblRptHdr) e.nextElement();
					m = new HashMap();
					m.put("code", hdr.getCode());
					m.put("name", hdr.getName());

					if (hdr.getContentType() == InsTblRptHdr.StringContent)
						m.put("type", "text");
					else if (hdr.getContentType() == InsTblRptHdr.IntegerContent) {
						m.put("type", "integer");
						m
								.put("formatCellValue",
										"isc.Format.toUSString(value)");
					} else if (hdr.getContentType() == InsTblRptHdr.DoubleContent) {
						m.put("type", "float");
						m
								.put("formatCellValue",
										"isc.Format.toUSString(value)");
					} else if (hdr.getContentType() == InsTblRptHdr.DateContent)
						m.put("type", "date");
					else if (hdr.getContentType() == InsTblRptHdr.ClobContent)
						m.put("type", "text");
					retHdrs.add(m);
				}

				for (int i = 0; data != null && i < data.length; i++) {
					m = new HashMap<String, Object>();
					InsTblRptRow row = (InsTblRptRow) data[i];
					IACompany c = IACompanyCache.getCompany(row.get(0)
							.toString(), us.getSubproductID());
					if (c != null) {
						m.put("company_code", c.getCompanyCode());
						m.put("company_code_dis", c.getCompanyCodeDis());
						m.put("group_code", c.getGroupCode());
						m.put("ins_type", c.getInsTypeInt());

					}
					for (int j = 0; j < row.getNumColumns(); j++) {
						m.put("c"+j,row.get(j)); 
					}
					rows.add(m);
				}
			}

			if (rpt != null)
				rpt.setData(null);
			if (ptiRpt != null)
				ptiRpt.setData(null);

		} catch (Exception e) {
			InsResourceMgr.getDefaultLog().logError(e);
		}

		dsResponse.setProperty("headers", retHdrs);
		dsResponse.setData(rows);
        dsResponse.setTotalRows(rows.size());
		return dsResponse;
	}
}
