package com.bankaudit.rest.process.dao;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.transform.ResultTransformer;
import org.jboss.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.bankaudit.dao.AbstractDao;
import com.bankaudit.dto.DataTableResponse;
import com.bankaudit.model.User;
import com.bankaudit.process.model.AuditSchedule;
import com.bankaudit.service.MaintEntityService;
import com.bankaudit.util.BankAuditUtil;

@Repository("auditReportReviewDao")
public class AuditReportReviewDaoImpl extends AbstractDao implements AuditReportReviewDao {
	
	@Autowired
	MaintEntityService maintEntityService;
	
	static final Logger logger = Logger.getLogger(MyAuditsDaoImpl.class);
	
	@SuppressWarnings("unchecked")
	@Override
	public DataTableResponse getReportReviewList(int legalEntityCode,String userId, String search, Integer orderColumn,	String orderDirection, Integer page, Integer size,
			LocalDate financialYear, String auditTypeCode, List<LocalDate>  financialYearStrtEndList) { // Added to filter the records based on Financial Year and AuditType
		Session session = getSession();
		session.setDefaultReadOnly(true);

		/********************** This block is to retrieve the User details --> UserId and UserName **************************/
		StringBuilder queryString0=new StringBuilder(// " Select concat(u.firstName , ' ' , u.lastName) as firstName, u.userId "
				 " from User u where u.legalEntityCode =:legalEntityCode ");
		
		Query query1=session.createQuery(queryString0.toString())
				.setParameter("legalEntityCode", legalEntityCode);
		
		List lst = query1.list();
		HashMap<String, String> userDtls = new HashMap<String, String>();
		for ( Iterator iter = lst.iterator(); iter.hasNext(); ) {
			User usr = (User) iter.next();
			if(usr.getUserId().equalsIgnoreCase(userId))
				userDtls.put(usr.getUserId(), "Me"); // for the same User we are stamping as "You"
			else userDtls.put(usr.getUserId(), (usr.getFirstName()==null?"":usr.getFirstName()) 
					+ (usr.getMiddleName()==null?"":(" "+usr.getMiddleName())) 
					+ (usr.getLastName()==null?"":(" "+usr.getLastName())) );		
		}
		logger.info("User details val is .... "+ userDtls);
		/******************** User Retrieval logic, Ends here ********************************/
		
		/*****To get the under lying entities ******/
		List<String> units= maintEntityService.getSubBranchesGyUserIdOrUnitId(legalEntityCode, "user", userId);
		
		/***** End here *****/
		
		String pattern = "yyyy-mm-dd hh:mm:ss";
       // SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
       				
		DataTableResponse dataTableResponse=new DataTableResponse();
		try {
		StringBuilder queryString=new StringBuilder("select sch as auditSchedule, " 
				+ "(select concat(auditTypeCode , '-' , auditTypeDesc) from MaintAuditTypeDesc at where at.auditTypeCode=sch.auditTypeCode and at.legalEntityCode= sch.legalEntityCode ) as auditTypeCode,"
				//+ " (Select concat(unitCode , '-' , unitName) from  MaintEntity e where e.unitCode =sch.unitId and e.legalEntityCode =sch.legalEntityCode ) as unitId,  "
				+ " (Select unitName from  MaintEntity e where e.unitCode =sch.unitId and e.legalEntityCode =sch.legalEntityCode ) as unitName,  "
				//+ " (Select g.description from  MaintEntity e,GeneralParameter g where e.unitCode =sch.unitId and e.legalEntityCode =sch.legalEntityCode and e.legalEntityCode =g.legalEntityCode and g.key1='UNIT_TYPE' and g.key2='UNIT_TYPE' and g.value=e.unitType) as unitType, "
				//+ " (Select c.criticalityDesc from  MaintEntity e,MaintCriticality c where e.unitCode =sch.unitId and e.legalEntityCode =sch.legalEntityCode and e.legalEntityCode =c.legalEntityCode and e.uCriticality=c.criticalityCode and c.criticalityOfType='Entity') as uCriticality, "
				
				//+ " (Select concat(u.firstName , ' ' , u.lastName) from  User u where u.userId =sch.unitHead and u.legalEntityCode =sch.legalEntityCode ) as unitHead, "
				+ " (Select t.userId from  AuditTeam t where t.auditId=sch.auditId and t.legalEntityCode =sch.legalEntityCode and t.userType='L') as teamLead, "
				
				//+ " (Select p.duration from  MaintEntity e,MaintAuditParameter p where e.unitCode =sch.unitId and e.unitType=p.unitType and e.uCriticality=p.uCriticality and sch.auditTypeCode=p.auditTypeCode and e.legalEntityCode =sch.legalEntityCode and e.legalEntityCode =p.legalEntityCode ) as duration, "
				//+ " (Select p.frequency from  MaintEntity e,MaintAuditParameter p where e.unitCode =sch.unitId and e.unitType=p.unitType and e.uCriticality=p.uCriticality and sch.auditTypeCode=p.auditTypeCode and e.legalEntityCode =sch.legalEntityCode and e.legalEntityCode =p.legalEntityCode ) as frequency "
				//+ " (select tm.auditTypeCode,GROUP_CONCAT(tm.name) from (Select t.auditTypeCode,t.planId, t.auditId, concat(u.firstName , ' ' , u.lastName) as name from  User u,AuditTeam t where u.userId =t.userId and t.auditId=sch.auditId and t.legalEntityCode =u.legalEntityCode and t.legalEntityCode =sch.legalEntityCode and t.userType='T') tm where  GROUP BY tm.auditTypeCode  ) as teamMember "
				//+ " (Select CASE WHEN COUNT(*) > 0 THEN 'Y' ELSE 'N' END as isUnitHeadUser from MaintEntity e where e.unitCode =sch.unitId and e.legalEntityCode =sch.legalEntityCode and e.unitHeadUser =:userId ) as isUnitHeadUser, "
				//+ " (Select CASE WHEN COUNT(*) > 0 THEN 'Y' ELSE 'N' END as isUnitHeadUser from UserRoleMapping urm where urm.userRoleId ='LRVWR' and urm.legalEntityCode =sch.legalEntityCode and urm.userId =:userId ) as isUnitHeadUser, "  // To check the user is a Lead Reviewer or not.
				//+ " (Select e.unitHeadUser from MaintEntity e where e.unitCode =sch.unitId and e.legalEntityCode =sch.legalEntityCode  ) as userHead, "
				+ "   (Select concat(sch.auditStatus , '-' , g.description) from  GeneralParameter g where g.legalEntityCode =sch.legalEntityCode and g.key1='STATUS' and g.key2='AUDIT_STATUS' and g.value=sch.auditStatus) as auditStatus, "
				+"    sch.reportStatus "
				+ ",  (Select concat(sch.reportStatus , '-' , g.description) from  GeneralParameter g where g.legalEntityCode =sch.legalEntityCode and g.key1='STATUS' and g.key2='REPORT_STATUS' and g.value=sch.reportStatus) as reportStatusDesc "
				//+ ", (Select count(*) from  AuditObservation o where o.legalEntityCode =sch.legalEntityCode and o.auditId=sch.auditId and o.complianceCategory='N' and o.reviewStatus='R') as responseReject "
				//+ ", (Select count(*) from  AuditObservation o where o.legalEntityCode =sch.legalEntityCode and o.auditId=sch.auditId and o.complianceCategory='C' and o.submissionStatus='A') as complianceCount "
				//+ ", (Select count(*) from  AuditObservation o where o.legalEntityCode =sch.legalEntityCode and o.auditId=sch.auditId and o.complianceCategory='NA' and o.submissionStatus='A') as notApplicableCount "
				+ ", sch.reportReviewer as reportReviewer "
				+ ",  (Select concat(sch.reportReviewer, '-',u.firstName , ' ' , u.lastName) from  User u where u.userId =sch.reportReviewer and u.legalEntityCode =sch.legalEntityCode ) as reportReviewerName "
				+ ", (Select g.description from  MaintEntity e,GeneralParameter g where e.unitCode =sch.unitId and e.legalEntityCode =sch.legalEntityCode and e.legalEntityCode =g.legalEntityCode and g.key1='UNIT_TYPE' and g.key2='UNIT_TYPE' and g.value=e.unitType) as unitType "
				//+ ", CONCAT(sch.assessedRiskPrcntg ,'-', sch.assessedRating) as assessedRating  "
				//+ ", CONCAT(sch.effectiveRiskPrcntg ,'-', sch.effectiveRating) as effectiveRating "
				//+ "  sch.auditStatus "
				
				
				+ ", (select group_concat(t.userId) from AuditTeam t where t.legalEntityCode=sch.legalEntityCode AND t.auditId=sch.auditId AND t.userType='M' ) AS teamMember "
				
				+ ", (Select concat(u.userId , '-' , ifnull(u.firstName,''), ' ',ifnull(u.middleName,''),' ',ifnull(u.lastName,'') ) "
				+ " from  User u where u.legalEntityCode =sch.legalEntityCode and u.userId=sch.maker) as maker, "
				
				+ " (Select c.criticalityDesc from  MaintEntity e,MaintCriticality c where e.unitCode =sch.unitId and e.legalEntityCode =sch.legalEntityCode"
				+ " and e.legalEntityCode =c.legalEntityCode and e.uCriticality=c.criticalityCode and c.criticalityOfType='Entity') as uCriticality "

				+ " from AuditSchedule sch , UserRoleMapping ur "
				+ "   where ur.legalEntityCode =sch.legalEntityCode and ur.userId=:userId  and " // Condition added to get the Reviewer list to only the Reviewer role
				// + "    and ur.userRoleId in ('RVWR','LRVWR') " // the Roles to change for RCSA Nabard
				/*+ " , User u where u.legalEntityCode =sch.legalEntityCode  "
				+ " and u.unitCode=sch.unitId and sch.legalEntityCode=u.legalEntityCode and  u.userId=:userId " */ // Need to be uncommented 
				+ "    sch.legalEntityCode =:legalEntityCode and ur.userRoleId IN ('G12') and " 
				+ "   ( IFNULL(sch.auditStatus,'NotNull') in ('AS','AR','AW','AC','AF')  OR  IFNULL(sch.reportStatus,'RIP') not in ('RIP','RRR') ) and "
				+ "   ( sch.unitId in (:units) or sch.reportReviewer =:userId )  "
				//+ "   and sch.unitId IN (SELECT u.unitCode FROM User u WHERE u.unitCode=sch.unitId and  u.legalEntityCode =sch.legalEntityCode and u.userId=:userId)" 
		        //+ " and  sch.auditTypeCode IN (SELECT asgm.auditTypeCode FROM MaintEntityAuditSubgroupMapping as asgm WHERE asgm.legalEntityCode=sch.legalEntityCode and asgm.mappingType='U' and asgm.id =:userId )" 
				); // To show the Assessments to which the Assessor Mapped (Department mapping)
		// + " and 1 = (select u.unitCode from User u where u.legalEntityCode=sch.legalEntityCode and u.userId=:userId) "); // temporary to check the Reviewer from Head Office
		
		// Financial Year and Audit Type filter added for filtering
		if(!BankAuditUtil.isEmptyString(auditTypeCode)) {
			queryString.append(" AND  sch.auditTypeCode =:auditTypeCode "); 
		}if(financialYear !=null) {
			LocalDate fYStartDt = financialYearStrtEndList.get(0);
			LocalDate fYearEndDt = financialYearStrtEndList.get(1);
			logger.info("fYStartDt :: "+fYStartDt+" fYEndDt :: "+fYearEndDt);
			queryString.append(" AND (sch.scheduleStartDate between '"+fYStartDt+"' AND '"+fYearEndDt+"' )");
			//queryString.append(" And (sch.scheduleStartDate between :fYStartDt and :fYearEndDt )");
		}
		
		logger.info("Before the qry....");
		
		if(!BankAuditUtil.isEmptyString(search)){
			queryString=queryString.append(" and ( "
					+ " sch.auditTypeCode IN (SELECT a.auditTypeCode FROM MaintAuditTypeDesc a  WHERE a.legalEntityCode=sch.legalEntityCode AND (a.auditTypeDesc LIKE :search OR a.auditTypeCode LIKE :search) ) "
					+ " or sch.planId like :search "
					+ " or sch.auditId like :search "
					+ " or sch.unitId IN (SELECT m.unitCode FROM MaintEntity m WHERE m.legalEntityCode=sch.legalEntityCode AND m.unitCode LIKE :search) "
					+ " or sch.unitId IN (SELECT m.unitCode FROM MaintEntity m WHERE m.legalEntityCode=sch.legalEntityCode AND m.unitName LIKE :search) "
					+ " or sch.unitId IN (SELECT m.unitCode FROM MaintEntity m,GeneralParameter g WHERE sch.unitId=m.unitCode and m.legalEntityCode=sch.legalEntityCode AND m.legalEntityCode =g.legalEntityCode and g.key1='UNIT_TYPE' and g.key2='UNIT_TYPE' and g.value=m.unitType and g.description LIKE :search) "
					+ " or sch.unitId IN (SELECT m.unitCode FROM MaintEntity m,MaintCriticality c WHERE sch.unitId=m.unitCode and m.legalEntityCode=sch.legalEntityCode AND m.legalEntityCode =c.legalEntityCode and m.uCriticality=c.criticalityCode and c.criticalityOfType='Entity' and  c.criticalityDesc LIKE :search) "
					+ " or sch.unitId IN (SELECT m.unitCode FROM MaintEntity m,MaintAuditParameter p WHERE sch.unitId=m.unitCode and m.legalEntityCode=sch.legalEntityCode AND m.legalEntityCode =p.legalEntityCode and m.uCriticality=p.uCriticality and sch.auditTypeCode=p.auditTypeCode and  p.duration LIKE :search) "
					+ " or sch.auditId IN (SELECT t.auditId FROM User u,AuditTeam t WHERE t.auditId=sch.auditId and t.legalEntityCode =sch.legalEntityCode and t.legalEntityCode =u.legalEntityCode and t.userId=u.userId and (t.userId Like :search or u.firstName LIKE :search or u.lastName Like :search) ) "
					+ " or sch.unitHead IN (SELECT u.userId FROM User u WHERE  sch.legalEntityCode =u.legalEntityCode and sch.unitHead=u.userId and (u.userId Like :search or u.firstName LIKE :search or u.lastName Like :search) ) "
					+ " or DATE_FORMAT(sch.scheduleStartDate, '%d %b %Y') LIKE :search "
					+ " or DATE_FORMAT(sch.scheduleEndDate, '%d %b %Y') LIKE :search "
					+ " or DATE_FORMAT(sch.actualStartDate, '%d %b %Y') LIKE :search "
					+ " or DATE_FORMAT(sch.actualEndDate, '%d %b %Y') LIKE :search "
					+ " or DATE_FORMAT(sch.lastAuditDate, '%d %b %Y') LIKE :search "
					+ " or sch.assessedRiskPrcntg like :search or sch.assessedRating like :search "
					+ " or sch.effectiveRiskPrcntg like :search or sch.effectiveRating like :search "
					+ " or sch.reviewStatus like :search "
					+ " or sch.auditId IN (select t.auditId from AuditTeam t, User u where t.legalEntityCode=sch.legalEntityCode AND t.auditId=sch.auditId AND t.userType='M' AND t.legalEntityCode=u.legalEntityCode AND t.userId=u.userId "
					+ "						AND sch.unitId=u.unitCode AND (u.firstName like :search OR u.middleName like :search OR u.lastName like :search OR u.userId like :search )) "
					
					+ " or sch.reportStatus IN (SELECT g.value FROM GeneralParameter g WHERE sch.legalEntityCode =g.legalEntityCode and g.key1='STATUS' "
							+ " and g.key2='REPORT_STATUS' and g.value=sch.reportStatus "
							+ " and (g.description LIKE :search or g.value LIKE :search) "
							 + " and sch.observationStatus !='AE'  " 
							+ " ) "
							
				    + " or sch.maker IN (SELECT u.userId FROM User u WHERE u.legalEntityCode =sch.legalEntityCode "
				    		+ " and (u.userId Like :search or u.firstName LIKE :search or u.lastName Like :search) )  " 
			
					+ " or sch.auditStatus IN (SELECT g.value FROM GeneralParameter g WHERE sch.legalEntityCode =g.legalEntityCode and g.key1='STATUS' "
							+ " and g.key2='AUDIT_STATUS' and g.value=sch.auditStatus "
							+ " and (g.description LIKE :search or g.value LIKE :search)"
						//	+ " and   ( sch.observationStatus !='AE'  ) "
							+ " ) "
							
					+ " or sch.auditStatus IN (SELECT g.value FROM GeneralParameter g WHERE sch.legalEntityCode =g.legalEntityCode and g.key1='STATUS' "
							+ " and g.key2='AUDIT_STATUS' and g.value=sch.auditStatus "
							+ " and (g.description LIKE :search or g.value LIKE :search)"
							+ " and   ( sch.observationStatus  ='AE' and sch.auditStatus='AW'  ) "
							+ " ) "
							
					+ "  " );
					
					if((search.length()==2 && search.toUpperCase().startsWith("EX") )
							|| (search.length()==3 && search.toUpperCase().startsWith("EXI"))
							|| (search.length()==4 && search.toUpperCase().startsWith("EXIT"))
							|| ((search.length()==5 || search.length()==6) && search.toUpperCase().startsWith("EXITE")) ){
						queryString.append("Or (sch.auditStatus='AI' and sch.observationStatus='AE' )");
					}
					
					queryString.append(" )" );
		}
		
	/*	queryString=queryString.append("  ORDER BY FIELD(sch.auditStatus, 'AI','AP','AC','AU') asc ");*/
		 
		String[] columns={
				"sch.auditTypeCode",
				"(sch.auditId *1 ), (sch.planId *1 )", //"CAST(planId AS Integer),CAST(auditId AS Integer) "
				"unitType",
				"(sch.unitId * 1) ",  //"unitId",
				"uCriticality",  
				"sch.duration",  // 5
				"sch.lastAuditDate",//last audit date actually 
				"sch.scheduleStartDate",
				"sch.scheduleEndDate",
				"sch.actualStartDate",
				"sch.actualEndDate",  // 10
				"teamLead", // Team Lead 
				"sch.maker",
				"sch.reportStatus",
				"sch.auditStatus",
				"unitName",   // 15
				"financialYear" 
		};
		
		if(orderColumn != null && orderColumn == -1 && !BankAuditUtil.isEmptyString(orderDirection)){ // -1 send for the first time from the UI during landing page.
			queryString=queryString.append(" ORDER BY "
					+ " FIELD(IFNULL(sch.reportStatus,'NoStatus'),'RAR','RUR') desc ,  "
					+ " FIELD( IFNULL(sch.auditStatus,'NoStatus') , 'AI','AS','AR','AC','AU','UP','NoStatus') asc  "); // The code modified to get the records in the order of Status on landing page, the sequence is  Initiated, Submitted, Respond, Reviewed, Closed
		}else if(orderColumn!=null
				&& !BankAuditUtil.isEmptyString(orderDirection)){
			queryString=queryString.append(" ORDER BY  ").append(columns[orderColumn]).append(" ").append(orderDirection);
		}else {
			queryString=queryString.append(" ORDER BY FIELD(sch.auditStatus, 'AI','AS','AR','AC','AU','UP') asc "); // Status AU & UP are the same
		}
		
		

		Query query=(Query) session.createQuery(queryString.toString())				
				.setResultTransformer(new ResultTransformer() {
					@Override
					public Object transformTuple(Object[] tuple, String[] aliases) {
						AuditSchedule auditSchedule=null;
						//System.out.println("tuple[0] ...."+tuple[0]);
						if(tuple[0]!=null){
							auditSchedule=(AuditSchedule)tuple[0];
							/* session.evict(maintEntity);*/
							
							if(tuple[1]!=null) auditSchedule.setAuditTypeCode(tuple[1].toString());
							if(tuple[2]!=null) {
								// auditSchedule.setUnitId(tuple[2].toString());
								//String unitCodeName=tuple[2].toString();
								//auditSchedule.setUnitId(unitCodeName);
								//auditSchedule.setUnitName(unitCodeName.substring(unitCodeName.indexOf('-')+1));								
								auditSchedule.setUnitId(auditSchedule.getUnitId()+"-"+tuple[2].toString());
								auditSchedule.setUnitName(tuple[2].toString());
							}
							
							if(tuple[3]!=null) {//auditSchedule.setTeamLead(userDtls.get(tuple[3].toString()));
								String teamLead = userDtls.get(tuple[3].toString());
								auditSchedule.setTeamLead(teamLead.equalsIgnoreCase("Me")?"Me":tuple[3].toString()+"-"+teamLead);
							}
							
							if(tuple[4]!=null) auditSchedule.setAuditStatus(tuple[4].toString());
							if(tuple[5]!=null) auditSchedule.setReportStatus(tuple[5].toString());
							if(tuple[6]!=null) auditSchedule.setReportStatusDesc(tuple[6].toString());
							if(tuple[7]!=null) auditSchedule.setReportReviewer(tuple[7].toString());
							if(tuple[8]!=null) auditSchedule.setReportReviewerName(tuple[8].toString());
							if(tuple[9]!=null) auditSchedule.setUnitType(tuple[9].toString());
							
							if(tuple[10]!=null){
								String teamMembers="";
								String[] members = tuple[10].toString().split(",");
								for (String member: members) {
									teamMembers+=member+"-"+userDtls.get(member)+",";
								}
								auditSchedule.setTeamMember(teamMembers.substring(0,teamMembers.length()-1));
							}
							
							if(tuple[11]!=null)	auditSchedule.setMaker(tuple[11].toString());
							
							if(tuple[12]!=null)	auditSchedule.setuCriticality(tuple[12].toString());
							
							
							
							/*if(tuple[8]!=null && auditSchedule.getRespondedFindings()!= null) {
								auditSchedule.setResponseReject(Integer.parseInt(tuple[8].toString()));
								auditSchedule.setRespondedFindings(auditSchedule.getRespondedFindings()- (Integer.parseInt(tuple[8].toString()))); // Included to find out the Responded Observations
							}
							else auditSchedule.setResponseReject(0);
						
							if(tuple[8]!=null) auditSchedule.setComplianceCount(Integer.parseInt(tuple[8].toString()));
							else auditSchedule.setComplianceCount(0);
						
							if(tuple[9]!=null)	auditSchedule.setNotApplicableCount(Integer.parseInt(tuple[9].toString()));
							else auditSchedule.setNotApplicableCount(0);
							
							if(tuple[10]!=null)	auditSchedule.setReportReviewer(tuple[10].toString());

							if(tuple[11]!=null)	auditSchedule.setUnitType(tuple[11].toString());*/
							
							//if(tuple[10]!=null)	auditSchedule.setAssessedRating(tuple[10].toString());
														
							//if(tuple[11]!=null)	auditSchedule.setEffectiveRiskPrcntg(tuple[11].toString());
							
							
							//auditSchedule.setUnitHead(auditSchedule.getUnitHead()+"-"+userDtls.get(auditSchedule.getUnitHead()));				
							
							/*if(tuple[12]!=null){
								String teamMembers="";
								String[] members = tuple[12].toString().split(",");
								for (String member: members) {
									teamMembers+=member+"-"+userDtls.get(member)+",";
								}
								auditSchedule.setTeamMember(teamMembers.substring(0,teamMembers.length()-1));
							}*/
							
							//int tmSize =0;
							/*if(auditSchedule.getAuditTeams() != null ) 
								tmSize= auditSchedule.getAuditTeams().size();
							String teamMember="";
							for( AuditTeam adtTm: auditSchedule.getAuditTeams() ) {
								adtTm.setUserId(adtTm.getUserId()+"-"+userDtls.get(adtTm.getUserId()));
								teamMember +=adtTm.getUserId() + ",";
							}if(tmSize >0 ) auditSchedule.setTeamMember(teamMember.substring(0,teamMember.lastIndexOf(",")));
							*/
							//System.out.println("Team size ...."+auditSchedule.getAuditTeams().size());
						}
						return auditSchedule;
					}
			@Override
			public List transformList(List collection) {
				return collection;
			}
		})		
				.setParameter("legalEntityCode",legalEntityCode).setParameter("userId", userId).setParameter("units", units);

		if(!BankAuditUtil.isEmptyString(search)){
			query.setParameter("search", "%"+search+"%");
		}
		if(!BankAuditUtil.isEmptyString(auditTypeCode)) {
			query.setParameter("auditTypeCode", auditTypeCode);
		}
		
		System.out.println("page :: "+page +"size :: "+ size);
		List<AuditSchedule> tmpAuditSchedule =query.list(); 
		Long totalRecords=null;
		try {
			totalRecords = (long)tmpAuditSchedule.size();
		}catch(Exception e) {
			totalRecords = (long)0;
		}
		List<AuditSchedule> auditSchedule=query.setFirstResult((page*size)).setMaxResults(size).list();
		
		System.out.println("Bfr size tmpAuditSchedule is .... "+tmpAuditSchedule.size()+" totalRecords:: "+ totalRecords);
		
		dataTableResponse.setData(auditSchedule);
		dataTableResponse.setRecordsTotal(totalRecords);
		dataTableResponse.setRecordsFiltered(totalRecords);
		
		}catch(Exception e) {
			e.printStackTrace(System.out);
		}
		return dataTableResponse;
			
	}	

}
