package ibase.webitm.ejb.sys;

import java.rmi.RemoteException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.w3c.dom.*;
import com.google.gwt.dom.client.Document;

import ibase.utility.BaseLogger;
import ibase.utility.E12GenericUtility;
import ibase.webitm.ejb.ValidatorEJB;
import ibase.webitm.utility.ITMException;

public class SubscriptionRenewalIC extends ValidatorEJB {
 E12GenericUtility genereicutility = new E12GenericUtility();
	
 public String itemChanged(String xmlString, String xmlString1, String xmlString2, String objContext, String currentColumn, String editFlag, String xtraParams) throws RemoteException 
	{
	 
		BaseLogger.log("3", null, null, " inside itemchange domparsing method");

		org.w3c.dom.Document dom = null;
		org.w3c.dom.Document dom1 = null;
		org.w3c.dom.Document dom2 = null;
		String errString = null;
		try
		{
			if (xmlString != null && xmlString.trim().length()!=0)
			{
				dom = genereicutility.parseString(xmlString);
			}
			if (xmlString1 != null && xmlString1.trim().length()!=0)
			{
				dom1 = genereicutility.parseString(xmlString1);
			}
			if (xmlString2 != null && xmlString2.trim().length()!=0)
			{
				dom2 = genereicutility.parseString(xmlString2);
			}
			
			//errString = itemChanged(dom1, dom2, objContext, currentColumn, editFlag, xtraParams);
			errString =  itemChanged(dom, dom1, dom2, objContext, currentColumn, editFlag, xtraParams);
			BaseLogger.log("3", null, null, " ErrString :" + errString);

		}
		catch (Exception e)
		{
			BaseLogger.log("3", null, null, " Exception :SfaTime :itemChanged(String,String):" + e.getMessage() );

			errString = genereicutility.createErrorString(e);
		}
		
		BaseLogger.log("3", null, null, "returning from SfaTime itemChanged" );
		return errString;
	}
 
 public String itemChanged(org.w3c.dom.Document dom, org.w3c.dom.Document dom1, org.w3c.dom.Document dom2, String objContext, String currentColumn,
			String editFlag, String xtraParams) throws RemoteException
	{
		
	 	BaseLogger.log("3", null, null, " Inside itemchange");
		Connection con = null;
		SimpleDateFormat sdf,simpledateformat; 
		int currentFormNo = 0, chrg_amtValues =0;
		String tranId = "",newDateString="" ,enterprise="",valid_upto = "", sql="",sql3="",renewPeriodLowerCase = "",enterprisesql="",validuptostring="", validupto = "", sql2= "", renewPeriod = "",enterpriseLowerCse = "",validuptoDateString="",demoDate = "11-AUG-23";
		List<String> enterprisesqllist = new ArrayList<>();
		PreparedStatement pstmt = null,pstmt2=null,pstmt3;
		int chrg_amt;
		ResultSet rs = null, rs2=null,rs3=null ;
		Date validuptoDate = null;
       // DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MMM-yyyy");
		StringBuffer valueXmlString = new StringBuffer();

		try {
			Calendar currentDate = Calendar.getInstance();
			simpledateformat = new SimpleDateFormat(genereicutility.getApplDateFormat());
			String sysDate = simpledateformat.format(currentDate.getTime());	
			Date datee = Calendar.getInstance().getTime() ;
			Date date = new Date();
			con = getConnection();	
			String currentdate = simpledateformat.format(date);
		 	List<Integer> chrg_amountlist = new ArrayList<>();
		 	Date currentDatee = new Date();
			String currntDate = simpledateformat.format(currentDatee);
		 	
		 	
			if (objContext != null && objContext.trim().length() > 0) {
				
				currentFormNo = Integer.parseInt(objContext);
			}
			
			valueXmlString = new StringBuffer("<?xml version=\"1.0\"?><Root><header><editFlag>");
			valueXmlString.append(editFlag).append("</editFlag></header>");
			
			switch(currentFormNo)
			{
			case 1:
				
				valueXmlString.append("<Detail1>");
				if ( currentColumn.trim().equalsIgnoreCase( "itm_default" )) {
			 	
					BaseLogger.log("3", null, null, "inside itm_default");

					tranId = checkNull(genereicutility.getColumnValue("tran_id", dom));

					
				//valueXmlString.append("<tran_date>").append("<![CDATA['"+sysDate+"']]>").append("</tran_date>");
				valueXmlString.append("<tran_date><![CDATA[").append(sysDate).append("]]></tran_date>\r\n");
				valueXmlString.append("<tran_id><![CDATA[").append(tranId).append("]]></tran_id>\r\n");

			}

				else if("itm_defaultedit".equalsIgnoreCase(currentColumn.trim()))
				{
					
				
					//valueXmlString.append("<ref_ser protect='1'><![CDATA[").append("").append("]]></ref_ser>\r\n");

					
				}

			
			else if("enterprise".equalsIgnoreCase(currentColumn.trim()))
			{
				
				
				
				BaseLogger.log("3", null, null, "  inside enterprise.equalsignorecase(correctcolumn.trim)");

				enterprise = checkNull(genereicutility.getColumnValue("enterprise", dom));
				//enterpriseLowerCse = enterprise.toLowerCase();
				BaseLogger.log("3", null, null, "  enterprise value"+enterprise);

				
				//check if this above enterprise exists in database	or not 
				
				sql = "select enterprise from entp_subs_renew";
				BaseLogger.log("3", null, null, "  sql to get enterprise from entp_subs_renew"+sql);
				pstmt = con.prepareStatement(sql);
				rs = pstmt.executeQuery();
				while(rs.next()) {
					
					enterprisesql =  rs.getString("enterprise") ;
					enterprisesqllist.add(enterprisesql);
					BaseLogger.log("3", null, null, "  enterprisesql"+enterprisesql );

				}
				BaseLogger.log("3", null, null, "  enterprisesqllist outside while "+enterprisesqllist );
				rs.close();
				rs = null;
				pstmt.close();
				pstmt = null;
				
				//enterprisesql = enterprisesql.toLowerCase();
				
				// if this above enterprise exists in database enterprise table 
				if(enterprisesqllist.contains(enterprise)) {
					
					BaseLogger.log("3", null, null, " enterprisesql.contains(enterprise)" );

						sql2 = "select max(valid_upto) from entp_subs_renew where enterprise = '"+enterprise+"' ";
						BaseLogger.log("3", null, null, "sql for max(validupto) "+sql2 );
						pstmt2 = con.prepareStatement(sql2);				
						rs2 = pstmt2.executeQuery();
							
							if(rs2.next()) {
								
							 validuptoDate =  rs2.getDate("max(valid_upto)");
							BaseLogger.log("3", null, null, " validupto"+validuptoDate );

							}		
							rs2.close();
							rs2 = null;
							pstmt2.close();
							pstmt2 = null;
							
							


							 validuptostring =  simpledateformat.format(validuptoDate);
							 BaseLogger.log("3", null, null, " validuptostring"+validuptostring );

							renewPeriod = checkNull(genereicutility.getColumnValue("renew_prd",dom));
							BaseLogger.log("3", null, null, " renewperiod"+renewPeriod );
							
							if(renewPeriod. contains("Y")) {
								BaseLogger.log("3", null, null, " inside renewperiod.contains(Y)" );

							int monthyearvalue = getMOnthOrYearVAlue(renewPeriod);
							BaseLogger.log("3", null, null, " getMOnthOrYearVAlue returning value "+monthyearvalue );
							
							Date dt =  simpledateformat.parse(validuptostring);
							currentDate.setTime(dt);
							
							currentDate.add(Calendar.YEAR, monthyearvalue);
							
							Date newdate =  currentDate.getTime();
							 newDateString =  simpledateformat.format(newdate);
							BaseLogger.log("3", null, null, " newdatestring "+newDateString );


							BaseLogger.log("3", null, null, " validuptostring inside renewperiod.contains(Y) "+validuptostring );

								
							}
							else if (renewPeriod.contains("M")) {
								BaseLogger.log("3", null, null, " inside renewperiod.contains(M)" );

								int monthyearvalue = getMOnthOrYearVAlue(renewPeriod);
								BaseLogger.log("3", null, null, " getMOnthOrYearVAlue returning value "+monthyearvalue );

								
								
								Date dt =  simpledateformat.parse(validuptostring);
								currentDate.setTime(dt);
								BaseLogger.log("3", null, null, " below currendate.settime in else if condition "+newDateString );

								currentDate.add(Calendar.MONTH, monthyearvalue);
								
								Date newdate =  currentDate.getTime();
								 newDateString =  simpledateformat.format(newdate);
								BaseLogger.log("3", null, null, " newdatestring IN ELSE IF  "+newDateString );
							}
							

				}
				
				else {
					
					BaseLogger.log("3", null, null, "inside else condition " );
		        
					BaseLogger.log("3", null, null, " currendate  "+currntDate );
					
					renewPeriod = checkNull(genereicutility.getColumnValue("renew_prd",dom));
					BaseLogger.log("3", null, null, " renewperiod"+renewPeriod );
				
					
					if(renewPeriod. contains("Y")) {
						BaseLogger.log("3", null, null, " inside renewperiod.contains(Y) in else condition" );

						int monthyearvalue = getMOnthOrYearVAlue(renewPeriod);
						BaseLogger.log("3", null, null, " getMOnthOrYearVAlue returning value "+monthyearvalue );

						
						
						Date dt =  simpledateformat.parse(currntDate);
						currentDate.setTime(dt);
						
						currentDate.add(Calendar.YEAR, monthyearvalue);
						
						Date newdate =  currentDate.getTime();
						 newDateString =  simpledateformat.format(newdate);
						BaseLogger.log("3", null, null, " newdatestring "+newDateString );
						
					}
					
					
					else if(renewPeriod. contains("M")) {
						BaseLogger.log("3", null, null, " inside renewperiod.contains(M) in else condition" );

						
						int monthyearvalue = getMOnthOrYearVAlue(renewPeriod);
						BaseLogger.log("3", null, null, " getMOnthOrYearVAlue returning value "+monthyearvalue );

						
						
						Date dt =  simpledateformat.parse(currntDate);
						currentDate.setTime(dt);
						BaseLogger.log("3", null, null, " below currendate.settime in else if condition "+newDateString );

						currentDate.add(Calendar.MONTH, monthyearvalue);
						
						Date newdate =  currentDate.getTime();
						 newDateString =  simpledateformat.format(newdate);
						BaseLogger.log("3", null, null, " newdatestring IN ELSE IF  "+newDateString );
						
					}
					
				}


				//String sql33 = "Select from "
				
				
				sql3 = "select enterprise, chrg_amt from ENTP_USER_LIC_CHRGS where enterprise = '"+enterprise +"' ";
				BaseLogger.log("3", null, null, "  sql3"+sql3);

				pstmt3 = con.prepareStatement(sql3);				
				rs3 = pstmt3.executeQuery();
					
					while(rs3.next()) {
						
					 chrg_amt =  rs3.getInt("chrg_amt");
					 chrg_amountlist.add(chrg_amt);
					BaseLogger.log("3", null, null, " chrg_amt"+chrg_amt );

					}
				
					
					for(int value :chrg_amountlist)
					{
						
						chrg_amtValues += value;
			            System.out.println(" chrg_amounlist values"+chrg_amtValues);

					}
					
			
				valueXmlString.append("<valid_upto><![CDATA[").append(newDateString).append("]]></valid_upto>\r\n");;
				valueXmlString.append("<renew_amt><![CDATA[").append(chrg_amtValues).append("]]></renew_amt>\r\n");;


			}
				
			//if renew_prd values changes then new value should be appended in valid_upto
			else if("renew_prd".equalsIgnoreCase(currentColumn.trim()))
			{
				
				valid_upto = checkNull(genereicutility.getColumnValue("valid_upto",dom));
				BaseLogger.log("3", null, null, "daniel valid_upto inside valid_upto. equalsignorecase"+valid_upto );

				if(valid_upto.trim().length() == 0)
				{
					
					valueXmlString.append("<valid_upto><![CDATA[").append("").append("]]></valid_upto>\r\n");;

				}
				
				
				
				else {
					
					renewPeriod = checkNull(genereicutility.getColumnValue("renew_prd",dom));
					BaseLogger.log("3", null, null, "daniel inside else of renew_prd.equalsignorecase  renewPeriod:: "+renewPeriod );

					
					if(renewPeriod. contains("Y")) {
						BaseLogger.log("3", null, null, "daniel inside renewperiod.contains(Y) in renewprd else condition" );

						int monthyearvalue = getMOnthOrYearVAlue(renewPeriod);
						BaseLogger.log("3", null, null, "daniel getMOnthOrYearVAlue returning value else of renewprd condition "+monthyearvalue );

						
						
						Date dt =  simpledateformat.parse(currntDate);
						currentDate.setTime(dt);
						
						currentDate.add(Calendar.YEAR, monthyearvalue);
						
						Date newdate =  currentDate.getTime();
						 newDateString =  simpledateformat.format(newdate);
						BaseLogger.log("3", null, null, " newdatestring renew_prd condition"+newDateString );
						
					}
					
					else if(renewPeriod. contains("M")) {
						BaseLogger.log("3", null, null, " inside renewperiod.contains(M) in renew_prd condition condition" );

						
						int monthyearvalue = getMOnthOrYearVAlue(renewPeriod);
						BaseLogger.log("3", null, null, " getMOnthOrYearVAlue returning value renew_prd condition"+monthyearvalue );

						
						
						Date dt =  simpledateformat.parse(currntDate);
						currentDate.setTime(dt);
						BaseLogger.log("3", null, null, " below currendate.settime in renew_prd condition "+newDateString );

						currentDate.add(Calendar.MONTH, monthyearvalue);
						
						Date newdate =  currentDate.getTime();
						 newDateString =  simpledateformat.format(newdate);
						BaseLogger.log("3", null, null, " newdatestring IN ELSE IF of renew_prd condition  "+newDateString );
						
					}
					
					valueXmlString.append("<valid_upto><![CDATA[").append(newDateString).append("]]></valid_upto>\r\n");;

					
				}
			
			}
				
				
				

			valueXmlString.append ("</Detail1>\r\n");
		}
			valueXmlString.append("</Root>\r\n");
	
	}
		
		
		catch(Exception e ) {
		 	BaseLogger.log("3", null, null, "Dan exception e "+e);
			e.printStackTrace();
		}
		
		finally {
			
			try {
				
				if(rs != null) 
				{
					rs.close();
					rs = null;
				}
				
				if(pstmt != null) 
				{
					pstmt.close();
					pstmt = null;

				}
				
				if(con != null)
				{
					
					con.close();
					con = null;
				}
				
				
			}
			catch (Exception ex) {	
					
				ex.printStackTrace();
			 	BaseLogger.log("3", null, null, "Dan exception e "+ex);

			}
			
		
			
		}
	 
	 return valueXmlString.toString();
	}
 
 
 public static int getMOnthOrYearVAlue (String renewPrd)
	{

	 	char renewPrdValue = renewPrd.charAt(0);
		System.out.println("renewPrdValue"+renewPrdValue);
		int value = Integer.parseInt(String.valueOf(renewPrdValue));
		
		
		return value;
	}
 
 public String checkNull(String inputStr) throws ITMException
	{
		try
		{
			if(inputStr != null && inputStr.trim().length() > 0)
			{
				return inputStr.trim();
			}
			else
			{
				return "";
			}
		}
		catch(Exception e)
		{
			BaseLogger.log("3", getUserInfo(), null,"Exception in checknull--["+e.getMessage()+"]");
			e.printStackTrace();
			throw new ITMException(e);
		}
	}
 
	
}
