package ibase.webitm.ejb.adm;

import ibase.system.config.ConnDriver;
import ibase.utility.E12GenericUtility;
import ibase.webitm.ejb.ActionHandlerEJB;
import ibase.webitm.ejb.ITMDBAccessEJB;
import ibase.webitm.utility.ITMException;

import java.rmi.RemoteException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.util.Calendar;

import javax.ejb.Stateless;

import org.w3c.dom.Document;

@Stateless
public class ITDeclarationDefault extends ActionHandlerEJB implements ITDeclarationDefaultLocal, ITDeclarationDefaultRemote {
	static E12GenericUtility genericUtility = new E12GenericUtility();
	@Override
	public String actionHandler(String actionType, String xmlString, String objContext, String xtraParams) throws RemoteException, ITMException {
		System.out.println("actionType[" + actionType + "]\n\txmlString[" + xmlString + "]\n\tobjContext[" + objContext + "]\n\txtraParams[" + xtraParams);
		Document dom = null;
		String retString = "";
		try{
			xmlString = xmlString == null ? "" : xmlString.trim();
			if(xmlString.length() > 0){
				dom = genericUtility.parseString(xmlString);
			}
			 if (actionType.equalsIgnoreCase("Default"))
		      {
		        retString = generateDefaultData(dom, objContext, xtraParams);
		      }
			//retString = generateDefaultData(dom, objContext, xtraParams);
			System.out.println(genericUtility.serializeDom(dom));
		} catch (Exception e) {
			System.out.println("Exception in " + this.getClass().getSimpleName() + ":" + e.getMessage());
		}
		System.out.println("Returning from " + this.getClass().getSimpleName() + "[" + retString + "]");
		return retString;
	}
	private String generateDefaultData(Document dom, String objContext, String xtraParams) {
		Connection conn = null;
		String pay_site = "", tran_id = "", sql = "", ad_code = "", ad_descr = "", userId = "", grade = "", cadre = "", sql1 = "", oldTranId = "", emp_code__decl = "", acct_prd = "";
		PreparedStatement pstmt = null, pstmt1 = null;
		ResultSet rs = null, rs1 = null;
		StringBuffer valueXmlBuff = new StringBuffer("<?xml version=\"1.0\"?>\r\n<Root>\r\n");
		
		try {
			ConnDriver con = new ConnDriver();
			conn = con.getConnectDB("Driver");
			
			int dom2Length = dom.getElementsByTagName("Detail2").getLength();
			if(dom2Length > 0) {
				ITMDBAccessEJB dbAccess = new ITMDBAccessEJB();
				System.out.println("Default Already Clicked or in Edit Mode");
				return dbAccess.getErrorString("", "VNODEFAULT", userId, "", conn);
			}
			
			
			userId = genericUtility.getValueFromXTRA_PARAMS(xtraParams, "loginCode");
			tran_id = checkNull(genericUtility.getColumnValue("tran_id", dom, "1"));
			
			String key_flag = "";
			sql = "select key_flag from transetup where tran_window = ? ";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, "w_emp_itdecl_byac");
			rs = pstmt.executeQuery();
			if(rs.next()) {
				key_flag = checkNull(rs.getString("key_flag")).trim();
			} else {
				key_flag = "A";
			}
			rs.close();
			rs = null;
			pstmt.close();
			pstmt = null;
			
			if(tran_id.trim().length() == 0 || "M".equalsIgnoreCase(key_flag)) {
				pay_site = checkNull(genericUtility.getColumnValue("pay_site", dom, "1"));
				grade = checkNull(genericUtility.getColumnValue("grade", dom, "1"));
				cadre = checkNull(genericUtility.getColumnValue("cadre", dom, "1"));
				emp_code__decl = checkNull(genericUtility.getColumnValue("emp_code__decl", dom, "1"));
				acct_prd = checkNull(genericUtility.getColumnValue("acct_prd", dom, "1"));
				
				AdmCommon admCommon = new AdmCommon();
				String admEnv = admCommon.getAdmEnv(pay_site, cadre, grade, "AD_CODE_DECL_TYPE", new Timestamp(Calendar.getInstance().getTimeInMillis()), conn);
				
				if("NULLFOUND".equalsIgnoreCase(admEnv)) {
					admEnv = admCommon.getEnv("999999", "AD_CODE_DECL_TYPE", conn);
				}
				
				
				
				if("A".equalsIgnoreCase(admEnv)) {
					sql = "select i.ad_code as ad_code, i.description as ad_descr from itdecl_fmt i join allwdedn a on a.ad_code = i.ad_code where i.access_to = 'A' order by i.seq_no";
				} else if("E".equalsIgnoreCase(admEnv)) {
					sql = "select i.ad_code as ad_code, i.description as ad_descr from itdecl_fmt i join allwdedn a on a.ad_code = i.ad_code where case when i.access_to = 'A' then 'A' else 'B' end <> 'A' order by i.seq_no";
				} else if("B".equalsIgnoreCase(admEnv)) {
					sql = "select i.ad_code as ad_code, i.description as ad_descr from itdecl_fmt i join allwdedn a on a.ad_code = i.ad_code order by i.seq_no";
				}
				
				pstmt = conn.prepareStatement(sql);
				rs = pstmt.executeQuery();
				
				sql1 = "select tran_id from (select tran_id from emp_itdecl_hdr where emp_code__decl = ? and acct_prd = ? and status = 'F' and qtr_no = '9' and confirmed = 'Y' and decl_type = 'D' order by chg_date desc) where rownum = 1";
				//sql1 = "select tran_id from emp_itdecl_hdr where qtr_no = '9' and decl_type ='D' AND emp_code__decl = ? AND acct_prd = ? and confirmed = 'Y' order by chg_date and rownum = 1";
				pstmt1 = conn.prepareStatement(sql1);
				pstmt1.setString(1, emp_code__decl);
				pstmt1.setString(2, acct_prd);
				rs1 = pstmt1.executeQuery();
				if(rs1.next()) {
					oldTranId = checkNull(rs1.getString("tran_id"));
				} else {
					oldTranId = "";
				}
				rs1.close();
				rs1 = null;
				pstmt1.close();
				pstmt1 = null;
				
				System.out.println("Existing tran_id to be loaded records from: [" + oldTranId + "]");
				
				int lineNo = 0;
				while(rs.next()){
					lineNo++;
					ad_code = checkNull(rs.getString("ad_code"));
					ad_descr = checkNull(rs.getString("ad_descr"));
					valueXmlBuff.append("<Detail>");
					if("M".equalsIgnoreCase(key_flag)) {
						valueXmlBuff.append("<tran_id>").append("<![CDATA[" + tran_id + "]]>").append("</tran_id>");
					} else {
						valueXmlBuff.append("<tran_id/>");
					}
					valueXmlBuff.append("<line_no>").append("<![CDATA[" + lineNo + "]]>").append("</line_no>");
					valueXmlBuff.append("<ad_code>").append("<![CDATA[" + ad_code + "]]>").append("</ad_code>");
					valueXmlBuff.append("<ad_descr>").append("<![CDATA[" + ad_descr + "]]>").append("</ad_descr>");
					if(oldTranId.length() > 0) {
						sql1 = "select amount_decl, amount_proof, amount_decl__old, amount_proof__old, remarks from emp_itdecl_det where tran_id = ? and ad_code = ?";
						pstmt1 = conn.prepareStatement(sql1);
						pstmt1.setString(1, oldTranId);
						pstmt1.setString(2, ad_code);
						rs1 = pstmt1.executeQuery();
						if(rs1.next()){
							String remarks = checkNull(rs1.getString("remarks")).trim();
							double amtDecl = rs1.getDouble("amount_decl");
							double amtProof = rs1.getDouble("amount_proof");
							if("null".equalsIgnoreCase(remarks) || remarks.length() == 0){
								remarks = "";
							}
							valueXmlBuff.append("<amount_decl>").append("<![CDATA[" + amtDecl + "]]>").append("</amount_decl>");
							valueXmlBuff.append("<amount_proof>").append("<![CDATA[" + amtProof + "]]>").append("</amount_proof>");
							valueXmlBuff.append("<amount_decl__old>").append("<![CDATA["+amtDecl+"]]>").append("</amount_decl__old>");
							valueXmlBuff.append("<amount_proof__old>").append("<![CDATA["+amtProof+"]]>").append("</amount_proof__old>");
							valueXmlBuff.append("<remarks>").append("<![CDATA[" + remarks + "]]>").append("</remarks>");
						} else {
							valueXmlBuff.append("<amount_decl>").append("<![CDATA[0]]>").append("</amount_decl>");
							valueXmlBuff.append("<amount_proof>").append("<![CDATA[0]]>").append("</amount_proof>");
							valueXmlBuff.append("<amount_decl__old>").append("<![CDATA[0]]>").append("</amount_decl__old>");
							valueXmlBuff.append("<amount_proof__old>").append("<![CDATA[0]]>").append("</amount_proof__old>");
							valueXmlBuff.append("<remarks>").append("<![CDATA[]]>").append("</remarks>");
						}
						rs1.close();
						rs1 = null;
						pstmt1.close();
						pstmt1 = null;
					} else {
						valueXmlBuff.append("<amount_decl>").append("<![CDATA[0]]>").append("</amount_decl>");
						valueXmlBuff.append("<amount_proof>").append("<![CDATA[0]]>").append("</amount_proof>");
						valueXmlBuff.append("<amount_decl__old>").append("<![CDATA[0]]>").append("</amount_decl__old>");
						valueXmlBuff.append("<amount_proof__old>").append("<![CDATA[0]]>").append("</amount_proof__old>");
						valueXmlBuff.append("<remarks>").append("<![CDATA[]]>").append("</remarks>");
					}
					valueXmlBuff.append("</Detail>");
				}
				rs.close();
				rs = null;
				pstmt.close();
				pstmt = null;
			}
			valueXmlBuff.append("</Root>\r\n");
			System.out.println("Returning from " + this.getClass().getSimpleName() +" : " + valueXmlBuff.toString());
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if(conn != null) {
					conn.close();
					conn = null;
				}
				if(rs != null) {
					rs.close();
					rs = null;
				}
				if(pstmt != null) {
					pstmt.close();
					pstmt = null;
				}
				System.out.println("Closed all Database Resource...!");
			} catch (Exception e) {
				System.out.println("Exception in EJB ["+this.getClass().getSimpleName()+"]::generateDefaultData::[" + e.getMessage()+"]");
			}
		}
		return valueXmlBuff.toString();
	}
	private String checkNull(String value) {
		return value == null ? "" : value.trim();
	}
}
