package ibase.webitm.ejb.fin;

import ibase.system.config.ConnDriver;
import ibase.utility.CommonConstants;
import ibase.webitm.ejb.ITMDBAccessEJB;
import ibase.webitm.ejb.ProcessEJB;
import ibase.webitm.utility.GenericUtility;
import ibase.webitm.utility.ITMException;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.rmi.RemoteException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

import javax.ejb.Stateless;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

@Stateless
public class ContributionProcess extends ProcessEJB implements
		ContributionProcessLocal, ContributionProcessRemote {

	public String process(String xmlString, String xmlString2,
			String windowName, String xtraParams) throws RemoteException,
			ITMException {
		System.out.println("^^^^^^^ Inside Contribution Process EJB -> Process Method 1 ^^^^^^^");
		Document detailDom = null;
		Document headerDom = null;
		GenericUtility genericUtility = GenericUtility.getInstance();
		ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();
		String retString = "";

		try {
			if (xmlString != null && xmlString.trim().length() != 0) {
				headerDom = genericUtility.parseString(xmlString);
			}
			if (xmlString2 != null && xmlString2.trim().length() != 0) {
				detailDom = genericUtility.parseString(xmlString2);
			}
			retString = process(headerDom, detailDom, windowName, xtraParams);
		} catch (Exception e) {
			System.out.println("Exception ContributionProcess Method 1");
			e.printStackTrace();
			retString = itmDBAccessEJB.getErrorString("", "VTCPFAIL", "", 1);
			throw new ITMException(e);
		}
		return retString;
	}

	public String process(Document headerDom, Document detailDom, String windowName, String xtraParams) throws RemoteException, ITMException {
	System.out.println("^^^^^^^ Inside Contribution Process -> Process Method 2 ^^^^^^^");
	String retString = "";
	StringBuffer xmlBuffer = new StringBuffer();
	
	NodeList parentNodeList = null;
	NodeList childNodeList = null;
	Node parentNode = null;
	Node childNode = null;
	ConnDriver connDriver = new ConnDriver();
	Connection connIns = null;
	Connection connSel=null;
	PreparedStatement pstmt = null;
	ResultSet rs=null;
	String sql = "";
	ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();
	boolean isError = false;
	int counter=0;
	String finEntity="", siteCodeFr="", siteCodeTo="", tranDateFr="", tranDateTo="";
	//1st
	double openingStk=0, closingStk=0;
	String siteCode="", city="";
	//2nd
	double purchases=0, sales=0, discount=0;
	String periodCode="";
	String tag="";
	
	String addquery="";
	String sqlFileOpenStk="",sqlFilePurVal="", sqlFileSalVal="", sqlFileDiscVal="", addFileQuery="" ;
	String acctCode="";
	
	double serNo=0;
	double margin=0;
	double percentage=0;
	
	int delCount=0;
	int countIns=0;
	String errString="";
	Timestamp fromDate=null;
	Timestamp beforDtFrom=null;
	Timestamp toDate=null;
	GenericUtility genericUtility=GenericUtility.getInstance();
	HashMap<String,String[]> contMap = new HashMap<String,String[]>();
	String keyStr="";
	//String valArray[]={"0","0","0","0"};
	String valArray[]=null;
	String sqlInsert="";
	SimpleDateFormat sdf=null;
	try {

		connIns = connDriver.getConnectDB("DriverDWH");
		connIns.setAutoCommit(false);
	    connDriver = null;
	    connDriver = new ConnDriver();
	    connSel = connDriver.getConnectDB("DriverITM");
	    connSel.setAutoCommit(false);
	    connDriver = null;
	    
	    parentNodeList = detailDom.getElementsByTagName("Detail1");
	    System.out.println("parent node list-->"+parentNodeList);
	    parentNode = parentNodeList.item(0);
	    System.out.println("parent node-->"+parentNode);
	    childNodeList = parentNode.getChildNodes();
	    for (int i = 0; i < childNodeList.getLength(); i++) {
			childNode = childNodeList.item(i);
			if ("fin_entity".equalsIgnoreCase(childNode.getNodeName())) {
			    finEntity = childNode.getFirstChild() == null ? "" : childNode.getFirstChild().getNodeValue();
			} else if ("site_code_from".equalsIgnoreCase(childNode.getNodeName())) {
				siteCodeFr = childNode.getFirstChild() == null ? "" : childNode.getFirstChild().getNodeValue();
			}else if ("site_code_to".equalsIgnoreCase(childNode.getNodeName())) {
				siteCodeTo = childNode.getFirstChild() == null ? "" : childNode.getFirstChild().getNodeValue();
			}else if ("tran_date_from".equalsIgnoreCase(childNode.getNodeName())) {
				tranDateFr = childNode.getFirstChild() == null ? "" : childNode.getFirstChild().getNodeValue();
			}else if ("tran_date_to".equalsIgnoreCase(childNode.getNodeName())) {
				tranDateTo = childNode.getFirstChild() == null ? "" : childNode.getFirstChild().getNodeValue();
			}
	    }
	    finEntity = finEntity == null ? "" : finEntity.trim();
	    siteCodeFr = siteCodeFr == null ? "" : siteCodeFr.trim();
	    siteCodeTo = siteCodeTo == null ? "" : siteCodeTo.trim();
	    tranDateFr = tranDateFr == null ? "" : tranDateFr.trim();
	    tranDateTo = tranDateTo == null ? "" : tranDateTo.trim();
	    sdf=new SimpleDateFormat("dd-MM-yy");
	    tranDateFr = genericUtility.getValidDateString(tranDateFr, genericUtility.getApplDateFormat(), genericUtility.getDBDateFormat());
	    fromDate = java.sql.Timestamp.valueOf(tranDateFr + " 00:00:00");
	    
	    tranDateTo = genericUtility.getValidDateString(tranDateTo, genericUtility.getApplDateFormat(), genericUtility.getDBDateFormat());
	    toDate = java.sql.Timestamp.valueOf(tranDateTo + " 00:00:00");
	    
		beforDtFrom=new Timestamp(fromDate.getTime()-1*24*3600*1000);
		
		//		
//	    sql="DELETE FROM CONTRIBUTION_SUMMARY WHERE SITE_CODE BETWEEN siteCodeFr AND siteCodeTo AND periodCode" +
//		 "IN(SELECT CODE FROM PERIOD WHERE FR_DATE>= tranDateFr AND TO_DATE<=tranDateTo)";
	    
		sql="DELETE FROM CONTRIBUTION_SUMMARY WHERE SITE_CODE BETWEEN ? AND ? AND SITE_CODE IN(SELECT SITE_CODE FROM SITE WHERE FIN_ENTITY=?) AND PRD_CODE " +
		   		 "IN(SELECT CODE FROM PERIOD WHERE FR_DATE>= ? AND TO_DATE<=?)";
	    pstmt = connIns.prepareStatement(sql);			
		pstmt.setString(1, siteCodeFr);
		pstmt.setString(2, siteCodeTo);
		pstmt.setString(3, finEntity);
		pstmt.setTimestamp(4, fromDate);
		pstmt.setTimestamp(5, toDate);
		delCount = pstmt.executeUpdate();
		pstmt.close();
		pstmt=null;
		
		System.out.println("delete count---->"+delCount); 
		
	    
	    sqlFileOpenStk = CommonConstants.JBOSSHOME + File.separator + "sql" + File.separator + "openingStockValue";
	    
	     addFileQuery=readFile(sqlFileOpenStk+".sql");
		 addquery=addFileQuery;
		// System.out.println("add query---->"+addquery);
		 System.out.println(addquery.contains("@fromDate@"));
		 addquery=addquery.replaceAll("@fromDate@", sdf.format(fromDate));
		 //System.out.println("from Date ----->"+fromDate.toString());
		 addquery=addquery.replaceAll("@prevDate@", sdf.format(beforDtFrom));
		// System.out.println(addquery.contains("@prevDate@"));
		 //System.out.println("PREVIOUSE DATE---->"+beforDtFrom.toString());
		 addquery=addquery.replaceAll("@toDate@", sdf.format(toDate));
		 //System.out.println(addquery.contains("@toDate@"));
		 addquery=addquery.replaceAll("@finEntity@", finEntity);
		// addquery=addquery.replaceAll("@acctCode@",acctCode);
		 addquery=addquery.replaceAll("@siteCodeFr@",siteCodeFr);
		 //System.out.println(addquery.contains("@siteCodeFr@"));
		 addquery=addquery.replaceAll("@siteCodeTo@",siteCodeTo);
		 //System.out.println(addquery.contains("@siteCodeTo@"));
		 addquery=addquery.replaceAll("@periodCode@", periodCode); 
		 //System.out.println("addquery----"+addquery);
		 
		 FileOutputStream fout = null;
			BufferedWriter bw = null;
			fout = new FileOutputStream("ContributionSummary.sql");
			bw = new BufferedWriter(new OutputStreamWriter(fout));
			bw.write(addquery);
			bw.close();
			fout.close();
			
			pstmt=connIns.prepareStatement(addquery);
	    	rs=pstmt.executeQuery();
	    	while(rs.next())
	    	{
	    		valArray=new String[4];
	    		siteCode=rs.getString("site_code");
	    		openingStk=rs.getDouble("op_stock");
	    		purchases=rs.getDouble("purchases");
	    		sales=rs.getDouble("sales");
	    		closingStk=rs.getDouble("cl_stock");
	    		discount=rs.getDouble("discount");
	    		periodCode=rs.getString("prd_code");
	    		tag=rs.getString("tag");
	    		keyStr=siteCode+"@"+periodCode;
	    		
	    		System.out.println("key string ---Opstk>"+keyStr);
	    		if(!contMap.containsKey(keyStr))
	    		{
	    			valArray[0]=openingStk+"";
	    			System.out.println("in inventory-----"+valArray[0]);
	    			contMap.put(keyStr, valArray);
	    		}
//	    		else
//	    		{
//	    			valArray=contMap.get(keyStr);
//	    			valArray[0]=openingStk+"";
//	    			contMap.put(keyStr, valArray);
//	    		}
	    		
	    	}
	    	
	    	pstmt.close();
	    	pstmt=null;
	    	rs.close();
	    	rs=null;
	    	
	    	sqlFilePurVal = CommonConstants.JBOSSHOME + File.separator + "sql" + File.separator + "purchaseValue";
		    
		     addFileQuery=readFile(sqlFilePurVal+".sql");
			 addquery=addFileQuery;
			 addquery=addquery.replaceAll("@tranDateFr@", sdf.format(fromDate));
			 addquery=addquery.replaceAll("@tranDateTo@", sdf.format(toDate));
			 addquery=addquery.replaceAll("@finEntity@", finEntity);
			 //addquery=addquery.replaceAll("@acctCode@",acctCode);
			 addquery=addquery.replaceAll("@siteCodeFr@",siteCodeFr);
			 addquery=addquery.replaceAll("@siteCodeTo@",siteCodeTo);
			 //addquery=addquery.replaceAll("@periodCode@", periodCode); 
			 System.out.println("add query for purchase--->"+addquery);
			 
			 pstmt=connSel.prepareStatement(addquery);
		     rs=pstmt.executeQuery();
		    	while(rs.next())
		    	{
		    		valArray=new String[4];
		    		siteCode=rs.getString("site_code");
		    		openingStk=rs.getDouble("op_stock");
		    		purchases=rs.getDouble("purchases");
		    		sales=rs.getDouble("sales");
		    		closingStk=rs.getDouble("cl_stock");
		    		discount=rs.getDouble("discount");
		    		periodCode=rs.getString("prd_code");
		    		tag=rs.getString("tag");
		    		keyStr=siteCode+"@"+periodCode;
		    		System.out.println("key Str in purchase---->"+keyStr);
		    		
		    		if(!contMap.containsKey(keyStr))
		    		{
		    			valArray[1]=purchases+"";
		    			System.out.println("in purchse--->"+valArray[1]);
		    			contMap.put(keyStr, valArray);
		    		}
		    		else
		    		{
		    			valArray=contMap.get(keyStr);
		    			valArray[1]=purchases+"";
		    			System.out.println("in purchase else--->"+valArray[1]);
		    			contMap.put(keyStr, valArray);
		    		}
		    	}
		    	pstmt.close();
		    	pstmt=null;
		    	rs.close();
		    	rs=null;
		    	
		    	
		    	sqlFileSalVal = CommonConstants.JBOSSHOME + File.separator + "sql" + File.separator + "salesValue";
			    
			     addFileQuery=readFile(sqlFileSalVal+".sql");
				 addquery=addFileQuery;
				 addquery=addquery.replaceAll("@tranDateFr@", sdf.format(fromDate));
				 addquery=addquery.replaceAll("@tranDateTo@", sdf.format(toDate));
				 addquery=addquery.replaceAll("@finEntity@", finEntity);
				 //addquery=addquery.replaceAll("@acctCode@",acctCode);
				 addquery=addquery.replaceAll("@siteCodeFr@",siteCodeFr);
				 addquery=addquery.replaceAll("@siteCodeTo@",siteCodeTo);
				 addquery=addquery.replaceAll("@periodCode@", periodCode); 
				// errString=insertContribution(addquery,connSel,connIns);
				 pstmt=connSel.prepareStatement(addquery);
				 rs=pstmt.executeQuery();
			    	while(rs.next())
			    	{
			    		valArray=new String[4];
			    		siteCode=rs.getString("site_code");
			    		openingStk=rs.getDouble("op_stock");
			    		purchases=rs.getDouble("purchases");
			    		sales=rs.getDouble("sales");
			    		closingStk=rs.getDouble("cl_stock");
			    		discount=rs.getDouble("discount");
			    		periodCode=rs.getString("prd_code");
			    		tag=rs.getString("tag");
			    		keyStr=siteCode+"@"+periodCode;
			    		System.out.println("key str in sales"+keyStr);
			    		if(!contMap.containsKey(keyStr))
			    		{
			    			valArray[2]=sales+"";
			    			contMap.put(keyStr, valArray);
			    			System.out.println("in sales if--->"+valArray[2]);
			    		}
			    		else
			    		{
			    			valArray=contMap.get(keyStr);
			    			valArray[2]=sales+"";
			    			contMap.put(keyStr, valArray);
			    			System.out.println("in else sales--->"+valArray[2]);
			    		}
			    	}
			    	pstmt.close();
			    	pstmt=null;
			    	rs.close();
			    	rs=null;
			    	sqlFileDiscVal = CommonConstants.JBOSSHOME + File.separator + "sql" + File.separator + "discountValue";
				    
				     addFileQuery=readFile(sqlFileDiscVal+".sql");
					 addquery=addFileQuery;
					 addquery=addquery.replaceAll("@tranDateFr@", sdf.format(fromDate));
					 addquery=addquery.replaceAll("@tranDateTo@", sdf.format(toDate));
					 addquery=addquery.replaceAll("@finEntity@", finEntity);
					 //addquery=addquery.replaceAll("@acctCode@",acctCode);
					 addquery=addquery.replaceAll("@siteCodeFr@",siteCodeFr);
					 addquery=addquery.replaceAll("@siteCodeTo@",siteCodeTo);
					 addquery=addquery.replaceAll("@periodCode@", periodCode); 
					 pstmt=connSel.prepareStatement(addquery);
					 rs=pstmt.executeQuery();
				    	while(rs.next())
				    	{
				    		valArray=new String[4];
				    		siteCode=rs.getString("site_code");
				    		openingStk=rs.getDouble("op_stock");
				    		purchases=rs.getDouble("purchases");
				    		sales=rs.getDouble("sales");
				    		closingStk=rs.getDouble("cl_stock");
				    		discount=rs.getDouble("discount");
				    		periodCode=rs.getString("prd_code");
				    		tag=rs.getString("tag");
				    		keyStr=siteCode+"@"+periodCode;
				    		System.out.println("key str in disc"+keyStr);
				    						    						    		
				    		if(!contMap.containsKey(keyStr))
				    		{
				    			System.out.println("not key present");
				    			valArray[3]=discount+"";
				    			contMap.put(keyStr, valArray);
				    			
				    		}
				    		else
				    		{
				    			System.out.println("key present");
				    			valArray=contMap.get(keyStr);
				    			valArray[3]=discount+"";
				    			contMap.put(keyStr, valArray);
				    		}
				    	}
				    	pstmt.close();
				    	pstmt=null;
				    	rs.close();
				    	rs=null;
				    	//errString=insertContribution(addquery,connSel,connIns);
				    	Set keyset=contMap.keySet();
						Iterator itr=keyset.iterator();
						
						System.out.println("value map---->"+contMap);
						while(itr.hasNext()){
						String key=(String)itr.next();
						String split[]=key.split("@");
						siteCode=split[0];
						periodCode=split[1];
						valArray=new String[4];
						System.out.println("site code"+siteCode);
						System.out.println("period code"+periodCode);
						
						
						valArray=contMap.get(key);
						System.out.println("valArray[0]-->"+valArray[0]);
						System.out.println("valArray[1]-->"+valArray[1]);
						System.out.println("valArray[2] ---->"+valArray[2]);
						System.out.println("valArray[3]--->"+valArray[3]);
						
						openingStk=Double.parseDouble(valArray[0]==null?"0":valArray[0]);
						System.out.println("OPENING STOCK---->"+openingStk);
						purchases=Double.parseDouble(valArray[1]==null?"0":valArray[1]);
						sales=Double.parseDouble(valArray[2]==null?"0":valArray[2]);
						discount=Double.parseDouble(valArray[3]==null?"0":valArray[3]);
						
						System.out.println("opening stock-->"+openingStk);
						System.out.println("purchase amt-->"+purchases);
						System.out.println("sales ---->"+sales);
						System.out.println("discount--->"+discount);
						
						if(openingStk!=0 || purchases !=0 || sales!=0 || discount !=0)
						{
							
				    	sqlInsert="insert into contribution_summary(site_code,op_stock,purchases,sales,cl_stock,discount,prd_code,tag)values(?,?,?,?,?,?,?,?) ";
			    		pstmt=connIns.prepareStatement(sqlInsert);
			    		pstmt.setString(1,siteCode);
			    		pstmt.setDouble(2, openingStk);
			    		pstmt.setDouble(3, purchases);
			    		pstmt.setDouble(4, sales);
			    		pstmt.setDouble(5,0);//closing stock
			    		pstmt.setDouble(6,discount);
			    		pstmt.setString(7,periodCode);
			    		pstmt.setString(8, " ");//tag
			    		countIns=pstmt.executeUpdate();
			    		System.out.println("count Insert--->"+countIns);
			    		pstmt.close();
			        	pstmt=null;
			        	
						}
			        	
					}
			}
catch (Exception e)
	{
	 
	    retString = itmDBAccessEJB.getErrorString("", "VMCPFAIL", "");
	    errString=retString;
	    throw new ITMException(e);
	} 
	
	finally {
	    try {
	    	
	    	if((errString==null || errString.trim().length()==0)&&(countIns>0)){
	    		connSel.commit();
	    		connIns.commit();
	    		errString=itmDBAccessEJB.getErrorString("", "VMCPSUCC", "");
	    	}
	    	else
	    	{
	    		
	    		connSel.rollback();
	    		connIns.rollback();	
	    		errString=itmDBAccessEJB.getErrorString("", "VMCPFAIL", "");
	  	    }
	    	if(pstmt!=null){
	    		pstmt.close();
	    		pstmt=null;
	    	}
	    	if(connSel!=null){
	    		connSel.close();
	    		connSel=null;
	    	}
	    	if(connIns!=null){
	    		connIns.close();
	    		connIns=null;
	    	}
	    }catch (Exception e) {
		throw new ITMException(e);
	    }
	}
	return errString;
    }

	/*
	 * Added for retrieving data from the sql file.
	 */
	private String readFile(String file) throws Exception {
		String sqlQry = "";
		String errString = "";
		try {
			// System.out.println("File "+file);
			FileInputStream fin = new FileInputStream(file);
			BufferedReader br = new BufferedReader(new InputStreamReader(fin));
			String tempStr = "";
			while ((tempStr = br.readLine()) != null) {
				sqlQry = sqlQry + tempStr;
			}
		} catch (FileNotFoundException fe) {
			System.out
					.println("FileNotFoundException :ContributionProcess :readFile(String).."
							+ fe.getMessage());
			fe.printStackTrace();
			errString = fe.getMessage();
			throw new ITMException(fe);
		}

		catch (Exception e) {
			System.out
					.println("Exception :ContributionProcess :readFile(String).."
							+ e.getMessage());
			e.printStackTrace();
			errString = e.getMessage();
			throw new ITMException(e);
		}
		return sqlQry;
	}
}