package ibase.webitm.ejb.fin;

import java.rmi.RemoteException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import ibase.utility.BaseLogger;
import ibase.utility.E12GenericUtility;
import ibase.webitm.ejb.ValidatorEJB;
import ibase.webitm.utility.ITMException;

public class AssetAssignIC extends ValidatorEJB {
	E12GenericUtility genericUtility = new E12GenericUtility();

	public String wfValData(String xmlString, String xmlString1, String xmlString2, String objContext, String editFlag,
			String xtraParams) throws RemoteException, ITMException {
		BaseLogger.log("3", getUserInfo(), null,
				">>>>>>>>>>>>>>>>>>AssetAssign validation called>>>>>>>>>>>>>>>>>>>:::");

		Document dom = null;
		Document dom1 = null;
		Document dom2 = null;
		String errString = null;
		System.out.println("xmlString[" + xmlString + "]");
		System.out.println("xmlString1[" + xmlString1 + "]");
		System.out.println("xmlString2[" + xmlString2 + "]");
		try {
			if (xmlString != null && xmlString.trim().length() != 0) {
				dom = genericUtility.parseString(xmlString);
			}
			if (xmlString1 != null && xmlString1.trim().length() != 0) {
				dom1 = genericUtility.parseString(xmlString1);
			}
			if (xmlString2 != null && xmlString2.trim().length() != 0) {
				dom2 = genericUtility.parseString(xmlString2);
			}
			errString = wfValData(dom, dom1, dom2, objContext, editFlag, xtraParams);
			System.out.println("ErrString: " + errString);
		} catch (Exception e) {
			System.out.println("Exception: AssetAssign: wfValData(String xmlString): " + e.getMessage() + ":");
			errString = genericUtility.createErrorString(e);
			e.printStackTrace();
		}
		System.out.println("Returning from AssetAssign wfValData");
		return (errString);
	}

	public String wfValData(Document dom, Document dom1, Document dom2, String objContext, String editFlag,
			String xtraParams) throws RemoteException, ITMException {
		BaseLogger.log("3", getUserInfo(), null, ">>>>>>>>>>>>>>>>>>AssetAssign validation called>>>>>>>>>>>>>>>>>>>");
		System.out.println("Inside AssetAssign validation");
		NodeList parentNodeList = null;
		NodeList childNodeList = null;
		Node parentNode = null;
		Node childNode = null;
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		PreparedStatement empCodeCountPstmt = null;
		ResultSet empCodeCountRs = null;
		PreparedStatement empCodeLCountPstmt = null;
		ResultSet empCodeLCountRs = null;
		PreparedStatement assetCodeCountPstmt = null;
		ResultSet assetCodeCountRs = null;
		String childNodeName = null;
		String errorString = "";
		String userId = "";
		int ctr = 0;
		int currentFormNo = 0;
		int childNodeListLength = 0;
		int batchCount = 0;
		String effectiveFrom;
		String validUpto;
		String assignStatus = "";
		String assectCode;
		String empCodeAssign = "";
		String empCodeLAssign = "";
		int assetCodeCount = 0;
		int empCodeCount = 0;
		int empCodeLCount = 0;


		SimpleDateFormat dtFormat = new SimpleDateFormat("dd/MM/yy");

		try {
			conn = getConnection();
			userId = getValueFromXTRA_PARAMS(xtraParams, "loginEmpCode"); // To get user details
			if (objContext != null && objContext.trim().length() > 0) {
				currentFormNo = Integer.parseInt(objContext);
			}

			// this will get all nodelist which start with Detail tag and form number ex.
			// Detail 1, Detail 2, Detail 3
			parentNodeList = dom.getElementsByTagName("Detail" + currentFormNo);

			// this will get single Detail tag at a time. ex. Detail 1
			parentNode = parentNodeList.item(0);

			// this will get all the childnode list which comes under the Detail tag.
			childNodeList = parentNode.getChildNodes();

			// this will get number of child nodes present in Detail tag.
			childNodeListLength = childNodeList.getLength();

			// used to iterate through child nodes
			for (ctr = 0; ctr < childNodeListLength; ctr++) {
				// fetch first tag which comes under the Detail tag ex.state_code
				childNode = childNodeList.item(ctr);

				// this will give name of that first node
				childNodeName = childNode.getNodeName();
				switch (currentFormNo) {
				case 1:
					if (childNodeName.equalsIgnoreCase("effective_from")) {
						if (childNode.getFirstChild() == null) // this will give you a value of selected node
						{
							errorString = getErrorString("effective_from", "VTCAMPNO2", userId);
							System.out.println("Inside check null condition");
							break;
						} else {
							// used to fetch field value from application form after click on finish
							effectiveFrom = genericUtility.getColumnValue("effective_from", dom);
							validUpto = genericUtility.getColumnValue("valid_upto", dom);
							effectiveFrom = effectiveFrom.trim();
							validUpto = validUpto.trim();
							BaseLogger.log("0", null, null, "effectiveFrom date [" + effectiveFrom + "]");
							BaseLogger.log("0", null, null, "validUpto date [" + validUpto + "]");

							try {
								java.util.Date formatedEffectiveFrom = dtFormat.parse(effectiveFrom);
								java.util.Date formatedValidUpto = dtFormat.parse(validUpto);

								if (formatedEffectiveFrom.compareTo(formatedValidUpto) > 0) {
									errorString = getErrorString("effective_from", "INVFROMUP ", userId);
								}
							} catch (ParseException pe) {
								BaseLogger.log("0", null, null, "Parsing error: " + pe.getMessage());
								errorString = "Invalid date format"; // Or handle it as needed
							}
						}
					}
					// Changes by Amol S on 17-MARCH-25 to add validation
					// else if ("E".equalsIgnoreCase(editFlag) ) {}

					else if (childNodeName.equalsIgnoreCase("ASSET_CODE")) {
						BaseLogger.log("3", null, null, " Inside the else block for Asset Code");

						assectCode = genericUtility.getColumnValue("asset_code", dom);
						BaseLogger.log("3", null, null, "Asset Code: [" + assectCode + "]");
						try {
							String sql = "SELECT COUNT(ASSET_CODE) AS COUNT FROM ASSET_REGISTER WHERE ASSET_CODE = ?";
							assetCodeCountPstmt = conn.prepareStatement(sql);
							assetCodeCountPstmt.setString(1, assectCode);
							assetCodeCountRs = assetCodeCountPstmt.executeQuery();
							if (assetCodeCountRs.next()) {
								assetCodeCount = assetCodeCountRs.getInt("COUNT");
							}
							if (assetCodeCount <= 0) {
								errorString = getErrorString("ASSET_CODE", "VTINVASET", userId);
							}
						} catch (SQLException e) {
							BaseLogger.log("3", null, null,
									"Catch block of asset code pophelp validation" + e.getMessage());
							e.printStackTrace();
						}

						if ("a".equalsIgnoreCase(editFlag)) {
							try {

								String sql = "SELECT ASSIGN_STATUS FROM ASSET_ASSIGN WHERE ASSET_CODE = ?";
								pstmt = conn.prepareStatement(sql);
								pstmt.setString(1, assectCode);
								rs = pstmt.executeQuery();

								if (rs.next()) {
									assignStatus = rs.getString("ASSIGN_STATUS");
								}
								BaseLogger.log("3", null, null, "Assign Status : [" + assignStatus + "]");

								if ("F".equalsIgnoreCase(assignStatus) || "R".equalsIgnoreCase(assignStatus)) {
									errorString = getErrorString("ASSIGN_STATUS", "ASSETSTUS ", userId);

								}
							} catch (SQLException e) {
								e.printStackTrace();
							}

						}
					}

					else if (childNodeName.equalsIgnoreCase("emp_code__assign")) {
						BaseLogger.log("3", null, null, " Inside the else block for emp_code__assign");

						empCodeAssign = genericUtility.getColumnValue("emp_code__assign", dom);
						BaseLogger.log("3", null, null, "emp_code__assign: [" + empCodeAssign + "]");
						try {
							String sql = "SELECT COUNT(CODE) AS COUNT FROM USERS WHERE CODE = ?";
							empCodeCountPstmt = conn.prepareStatement(sql);
							empCodeCountPstmt.setString(1, empCodeAssign);
							empCodeCountRs = empCodeCountPstmt.executeQuery();
							if (empCodeCountRs.next()) {
								empCodeCount = empCodeCountRs.getInt("COUNT");
							}
							if (empCodeCount <= 0) {
								errorString = getErrorString("emp_code__assign", "VTINVEMP0", userId);
							}
						} catch (SQLException e) {
							BaseLogger.log("3", null, null,
									"Catch block of emp_code__assign pophelp validation" + e.getMessage());
							e.printStackTrace();
						}
					}
					else if (childNodeName.equalsIgnoreCase("empcode__last_assign")) {
						BaseLogger.log("3", null, null, " Inside the else block for empcode__last_assign");

						empCodeLAssign = genericUtility.getColumnValue("empcode__last_assign", dom);
						BaseLogger.log("3", null, null, "empcode__last_assign: [" + empCodeLAssign + "]");
						try {
				
							String sql = "SELECT COUNT(EMP_CODE__ASSIGN) AS COUNT FROM ASSET_ASSIGN WHERE EMP_CODE__ASSIGN = ?";
							empCodeLCountPstmt = conn.prepareStatement(sql);
							empCodeLCountPstmt.setString(1, empCodeLAssign);
							empCodeLCountRs = empCodeLCountPstmt.executeQuery();
							if (empCodeLCountRs.next()) {
								empCodeLCount = empCodeLCountRs.getInt("COUNT");
							}
							if (empCodeLCount <= 0) {
								errorString = getErrorString("empcode__last_assign", "INVLEMPCO", userId);
							}
						} catch (SQLException e) {
							BaseLogger.log("3", null, null,
									"Catch block of empcode__last_assign pophelp validation" + e.getMessage());
							e.printStackTrace();
						}
					}
				}
			}
		} catch (Exception e) {
			System.out.println("Exception: AssetAssign: wfValData: " + e.getMessage() + ":");
			e.printStackTrace();
		} finally {
			closeResources(rs, pstmt, conn);
			closeResources(assetCodeCountRs, assetCodeCountPstmt, conn);
			closeResources(empCodeCountRs, empCodeCountPstmt, conn);
			closeResources(empCodeLCountRs, empCodeLCountPstmt, conn);


		}
		return errorString;
	}

	public String itemChanged(String xmlString, String xmlString1, String xmlString2, String objContext,
			String currentColumn, String editFlag, String xtraParams) throws RemoteException, ITMException {
		BaseLogger.log("3", getUserInfo(), null,
				">>>>>>>>>>>>>>>>>> AssetAssign itemchange called1>>>>>>>>>>>>>>>>>>>");
		Document dom = null;
		Document dom1 = null;
		Document dom2 = null;
		String errString = null;
		try {
			if (xmlString != null && xmlString.trim().length() != 0) {
				dom = genericUtility.parseString(xmlString);
			}
			if (xmlString1 != null && xmlString1.trim().length() != 0) {
				dom1 = genericUtility.parseString(xmlString1);
			}
			if (xmlString2 != null && xmlString2.trim().length() != 0) {
				dom2 = genericUtility.parseString(xmlString2);
			}
			errString = itemChanged(dom, dom1, dom2, objContext, currentColumn, editFlag, xtraParams);
			System.out.println("ErrString :" + errString);
		} catch (Exception e) {
			System.out.println("Exception :AssetAssign :itemChanged(String,String):" + e.getMessage() + ":");
			errString = genericUtility.createErrorString(e);
		}
		System.out.println("returning from AssetAssign itemChanged");
		return errString;
	}

	public String itemChanged(Document dom, Document dom1, Document dom2, String objContext, String currentColumn,
			String editFlag, String xtraParams) throws RemoteException, ITMException {
		BaseLogger.log("3", getUserInfo(), null, ">>>>>>>>>>>>>>>>>> AssetAssign itemchange called>>>>>>>>>>>>>>>>>>>");
		System.out.println("Inside itemchange");
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		StringBuffer valueXmlString = null;
		int currentFormNo = 0;
		String userId = "";
		String sql = "";
		try {
			conn = getConnection();
			userId = getValueFromXTRA_PARAMS(xtraParams, "loginEmpCode"); // To get user details after login
			if (objContext != null && objContext.trim().length() > 0) {
				currentFormNo = Integer.parseInt(objContext);
			}

			// start creating xml
			valueXmlString = new StringBuffer("<?xml version=\"1.0\"?><Root><header><editFlag>");
			valueXmlString.append(editFlag).append("</editFlag></header>");
			switch (currentFormNo) {
			case 1:
				valueXmlString.append("<Detail1>");
				if ("itm_default".equalsIgnoreCase(currentColumn.trim())) {
					BaseLogger.log("3", null, null, "AssetAssignIC in itm default ");
					DateFormat dtFormat = new SimpleDateFormat(getApplDateFormat());
					java.util.Date date = Calendar.getInstance().getTime();
					String currentDate = dtFormat.format(date);
					System.out.println("Current Date for Oracle: " + currentDate);
					valueXmlString.append("<tran_date protect = '1'>").append("<![CDATA[" + currentDate + "]]>")
							.append("</tran_date>");
				}
				if ("asset_code".equalsIgnoreCase(currentColumn.trim())) {
					String assetDescr = "";
					String assetCode = checkNull(genericUtility.getColumnValue("asset_code", dom));
					{
						sql = "select descr from asset_register where asset_code = ? ";

						pstmt = conn.prepareStatement(sql);
						pstmt.setString(1, assetCode);
						rs = pstmt.executeQuery();
						if (rs.next()) {
							assetDescr = rs.getString("descr");
						}
						rs.close();
						rs = null;
						pstmt.close();
						pstmt = null;
						BaseLogger.log("3", getUserInfo(), null, "Asset descriptionss::" + assetDescr);
						valueXmlString.append("<descr>").append("<![CDATA[" + assetDescr + "]]>").append("</descr>");
					}
				}
				if ("emp_code__assign".equalsIgnoreCase(currentColumn.trim())) {
					BaseLogger.log("3", getUserInfo(), null, "In emp_code__assign condition");
					String empFname = "";
					String empLname = "";
					String empCode = checkNull(genericUtility.getColumnValue("emp_code__assign", dom));
					{
						sql = "select emp_fname, emp_lname from employee where emp_code = ?";

						pstmt = conn.prepareStatement(sql);
						pstmt.setString(1, empCode);
						rs = pstmt.executeQuery();
						if (rs.next()) {
							empFname = rs.getString("emp_fname");
							empLname = rs.getString("emp_lname");
						}
						rs.close();
						rs = null;
						pstmt.close();
						pstmt = null;
						BaseLogger.log("3", getUserInfo(), null, "employee name::" + empFname + " " + empLname);
						valueXmlString.append("<emp_fname>").append("<![CDATA[" + empFname + " " + empLname + "]]>")
								.append("</emp_fname>");
					}
				}
				if ("empcode__last_assign".equalsIgnoreCase(currentColumn.trim())) {
					BaseLogger.log("3", getUserInfo(), null, "In empcode__last_assign condition");
					String empFname = "";
					String empLname = "";
					String empLCode = checkNull(genericUtility.getColumnValue("empcode__last_assign", dom));
					{
						sql = "select emp_fname, emp_lname from employee where emp_code = ?";
						pstmt = conn.prepareStatement(sql);
						pstmt.setString(1, empLCode);
						rs = pstmt.executeQuery();
						if (rs.next()) {
							empFname = rs.getString("emp_fname");
							empLname = rs.getString("emp_lname");
						}
						rs.close();
						rs = null;
						pstmt.close();
						pstmt = null;
						BaseLogger.log("3", getUserInfo(), null, "last employee name:::" + empFname + " " + empLname);
						valueXmlString.append("<emp_lname>").append("<![CDATA[" + empFname + " " + empLname + "]]>")
								.append("</emp_lname>");
					}
				}

				//

				if ("itm_defaultedit".equalsIgnoreCase(currentColumn.trim())) {
					System.out.println("Inside itm_default Test >>>>>>>>>>");
					System.out.println("Inside itm_default >>>>>>>>>>" + editFlag);

					if ("E".equalsIgnoreCase(editFlag)) {

						String assetCode = checkNull(genericUtility.getColumnValue("asset_code", dom));
						String empCode = checkNull(genericUtility.getColumnValue("emp_code__assign", dom));
						String empLCode = checkNull(genericUtility.getColumnValue("empcode__last_assign", dom));
						String assignStatus = checkNull(genericUtility.getColumnValue("assign_status", dom));

						valueXmlString.append("<asset_code protect='1'>").append("<![CDATA[" + assetCode + "]]>")
								.append("</asset_code>\r\n");
						valueXmlString.append("<emp_code__assign protect='1'>").append("<![CDATA[" + empCode + "]]>")
								.append("</emp_code__assign>\r\n");
						valueXmlString.append("<empcode__last_assign protect='1'>")
								.append("<![CDATA[" + empLCode + "]]>").append("</empcode__last_assign>\r\n");
						valueXmlString.append("<assign_status protect='1'>").append("<![CDATA[" + assignStatus + "]]>")
								.append("</assign_status>\r\n");

					}
				}

				//
				valueXmlString.append("</Detail1>\r\n");
				break;
			}
			valueXmlString.append("</Root>\r\n");
		} catch (Exception e) {
			System.out.println("Exception :AssetAssign :itemChanged(Document,String):" + e.getMessage() + ":");
			e.printStackTrace();
		} finally {
			closeResources(rs, pstmt, conn);
		}
		return valueXmlString.toString();
	}

	private void closeResources(ResultSet rs, PreparedStatement pstmt, Connection conn) {
		if (rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if (pstmt != null) {
			try {
				pstmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	private String checkNull(String input) {
		if (input == null) {
			input = "";
		} else {
			input = input.trim();
		}
		return input;
	}
}