package com.bankaudit.dao;

import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Date;

import org.hibernate.Session;
import org.jboss.logging.Logger;
import org.springframework.stereotype.Repository;

@Repository("businessDateDao")
public class BusinessDateDaoImpl extends AbstractDao implements BusinessDateDao{

	static final Logger logger = Logger.getLogger(BusinessDateDaoImpl.class);
	
	@Override
	public Date getBusinessDateTimestampByLegalEntityCode(Integer legalEntityCode) {
	
		Session session = getSession();
		Date date= (Date)session.createQuery("select bd.businessDate  from BusinessDate bd"
				+ " where bd.legalEntityCode =:legalEntityCode").setParameter("legalEntityCode", legalEntityCode)
				.uniqueResult();
		
		Date currentDate=new Timestamp(System.currentTimeMillis());
	
		  Calendar cal = Calendar.getInstance();  
	        cal.setTime(date);  
	        cal.set(Calendar.HOUR_OF_DAY, currentDate.getHours());  
	        cal.set(Calendar.MINUTE, currentDate.getMinutes());  
	        cal.set(Calendar.SECOND, currentDate.getSeconds());  
	        date= cal.getTime(); 
		
		return date;
		
	}
	
	@Override
	public void updateBusinessDateBasedOnSysDate(Integer legalEntityCode) {
		
		Session session=getSession();
		boolean isDeptAsRMD = false;
		Integer isBsnsDtSysDtSameCnt =0;
		logger.info("Inside updateBusinessDateBasedOnSysDate .. "+ legalEntityCode);
		try {
			isBsnsDtSysDtSameCnt = Integer.parseInt((session.createQuery("SELECT COUNT(*)  FROM BusinessDate WHERE "
					+ " legalEntityCode =:legalEntityCode "
					+ " AND businessDate <> DATE(sysdate()) ")
					.setParameter("legalEntityCode", legalEntityCode).uniqueResult()).toString());
			logger.info(" isBsnsDtSysDtSameCnt cnt .. "+ isBsnsDtSysDtSameCnt);
			
		}catch(Exception e) {
			e.printStackTrace(System.out);
		}
		logger.info("isBsnsDtSysDtSameCnt .. "+isBsnsDtSysDtSameCnt);
		try {
			if(isBsnsDtSysDtSameCnt > 0) {
				logger.info("Inside Business Date update ");
				session.createQuery("update BusinessDate b set "
						+ " b.businessDate= DATE(sysdate()) , "
						+ " b.processDate = DATE(sysdate()) "
						+ " where b.legalEntityCode =:legalEntityCode ")
				.setParameter("legalEntityCode", legalEntityCode).executeUpdate();
			}
		}catch(Exception e) {
			e.printStackTrace(System.out);
		}
		
	}

}
