package ibase.webitm.ejb.sys;

import java.rmi.RemoteException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.ejb.Stateless;

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

import ibase.utility.BaseLogger;
import ibase.utility.CommonConstants;
import ibase.utility.E12GenericUtility;
import ibase.utility.GenericUtility;
import ibase.utility.UserInfoBean;
import ibase.webitm.ejb.ITMDBAccessEJB;
import ibase.webitm.ejb.ValidatorEJB;
import ibase.webitm.utility.ITMException;

@Stateless
public class ExternalAPI extends ValidatorEJB {
    protected static String database = CommonConstants.DB_NAME;

    @Override
    public String wfValData(String xmlString, String xmlString1, String xmlString2, String objContext, String editFlag,
            String xtraParams) throws RemoteException, ITMException {
        BaseLogger.log("3", null, null, "Inside the ExternalAPI class is::");
        ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();

        Document dom = null;
        Document dom1 = null;
        Document dom2 = null;
        String errString = "";
        GenericUtility genericUtility = GenericUtility.getInstance();
        try {
            BaseLogger.log("3", null, null, "xmlString:::" + xmlString);

            if (xmlString != null && xmlString.length() != 0) {
                dom = genericUtility.parseString(xmlString);
            }
            if (xmlString1 != null && xmlString1.length() != 0) {
                dom1 = genericUtility.parseString(xmlString1);
            }
            if (xmlString2 != null && xmlString2.length() != 0) {
                dom2 = genericUtility.parseString(xmlString2);
            }
            errString = wfValData(dom, dom1, dom2, objContext, editFlag, xtraParams);
        } catch (Exception e) {
            // Handle the exception appropriately
        }
        return errString;
    }

    @Override
    public String wfValData(Document dom, Document dom1, Document dom2, String objContext, String editFlag,
            String xtraParams) throws RemoteException, ITMException {
        BaseLogger.log("3", null, null, " inside the wfvaldata::");
        Connection conn = null;
        ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();

        NodeList parentNodeList = null;
        NodeList childNodeList = null;
        Node parentNode = null;
        Node childNode = null;
        UserInfoBean userInfo = super.getUserInfo();
        int ctr = 0, currentFormNo = 0, childNodeListLength = 0;
        String childNodeName = null;
        GenericUtility genericUtility = GenericUtility.getInstance();
        E12GenericUtility utility = new E12GenericUtility();

        String errString = "";
        String userId = "";
        try {
            userId = getValueFromXTRA_PARAMS(xtraParams, "loginCode");
            SimpleDateFormat sdf = new SimpleDateFormat(genericUtility.getApplDateFormat());
            if (objContext != null && objContext.trim().length() > 0) {
                currentFormNo = Integer.parseInt(objContext);
            }
            BaseLogger.log("3", null, userInfo.getLoginCode(),
                    "****Validation for empty inputs Formno Ams=" + currentFormNo);
            switch (currentFormNo) {
                case 1:
                    BaseLogger.log("3", null, null, " inside the switchcase::");

                    parentNodeList = dom.getElementsByTagName("Detail" + currentFormNo);

                    parentNode = parentNodeList.item(0);
                    childNodeList = parentNode.getChildNodes();
                    childNodeListLength = childNodeList.getLength();

                    for (ctr = 0; ctr < childNodeListLength; ctr++) {
                        childNode = childNodeList.item(ctr);
                        BaseLogger.log("3", null, null, "Child Node=>" + ctr + "=>" + childNode);
                        childNodeName = childNode.getNodeName().trim();
                        BaseLogger.log("3", null, null, "Child Node Name=>" + ctr + "=>" + childNodeName);
                        BaseLogger.log("3", null, null,
                                "Child Node Value=>" + ctr + "=>" + genericUtility.getColumnValue(childNodeName, dom));

                        if (childNodeName.equalsIgnoreCase("eff_from")) {
                            Date fromDate = sdf.parse(genericUtility.getColumnValue("eff_from", dom));
                            Date toDate = sdf.parse(genericUtility.getColumnValue("valid_upto", dom));
                            BaseLogger.log("3", null, null, "fromDate is [" + fromDate + "]");
                            BaseLogger.log("3", null, null, "toDate is [" + toDate + "]");

                            if (fromDate.compareTo(toDate) > 0) {
                                errString = getErrorString("valid_upto", "DATEXEPT", userId);
                            }
                        }

                        if (childNodeName.equalsIgnoreCase("enterprise")) {
                            BaseLogger.log("3", null, null, "--gsb-- FirstChild::" + childNode.getFirstChild());

                            int objCount = 0;
                            String enterpriseValue = E12GenericUtility
                                    .checkNull(utility.getColumnValue("enterprise", dom));
                            System.out.println("Inside the enterprise validation::" + database);
                            String objSQL = "SELECT COUNT(*) AS COUNT FROM ENTERPRISE WHERE ENTERPRISE = ?";

                            try (Connection connection = getConnection();
                                PreparedStatement preparedStatement = connection.prepareStatement(objSQL)) {
                                preparedStatement.setString(1, enterpriseValue);

                                try (ResultSet resultSet = preparedStatement.executeQuery()) {
                                    if (resultSet.next()) {
                                        int count = resultSet.getInt("COUNT");

                                        if (count == 0) {
                                            errString = itmDBAccessEJB.getErrorString("enterprise", "INVLDENTPZ",
                                                    userId, "", conn);
                                            return errString;
                                        }
                                    }
                                }
                            } catch (SQLException e) {
                                e.printStackTrace(); 
                            } catch (Exception e) {
                                e.printStackTrace(); 
                            }
                        }
                    }
            }
        } catch (Exception e) {
        }

        return errString;
    }

    public static String checkNull(String input) {
        if (input == null || "null".equalsIgnoreCase(input) || "undefined".equalsIgnoreCase(input)) {
            input = "";
        }
        return input.trim();
    }
}
