package com.bankaudit.dao;

import java.util.Collections;
import java.util.Date;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.ScrollMode;
import org.hibernate.ScrollableResults;
import org.hibernate.Session;
import org.hibernate.transform.ResultTransformer;
import org.jboss.logging.Logger;
import org.springframework.stereotype.Repository;

import com.bankaudit.constants.BankAuditConstant;
import com.bankaudit.dto.DataTableResponse;
import com.bankaudit.model.MaintResidualRisk;
import com.bankaudit.util.BankAuditUtil;

import java.util.ArrayList;

@Repository("maintResidualRiskDao")
public class MaintResidualRiskDaoImpl extends AbstractDao implements MaintResidualRiskDao{

	static final Logger logger = Logger.getLogger(MaintResidualRiskDaoImpl.class);
	
	@SuppressWarnings("unchecked")
	@Override
	public List<MaintResidualRisk> getMaintResidualRisksExceptThis(Integer legalEntityCode, String residualRiskCode) {
		Session session=getSession();
		return session.createQuery("from MaintResidualRisk where "
				+ " legalEntityCode !=:legalEntityCode and "
				+ " residualRiskCode !=:residualRiskCode")
		.setParameter("legalEntityCode", legalEntityCode)
		.setParameter("residualRiskCode", residualRiskCode).list();
		

	}

	@Override
	public DataTableResponse getMaintResidualRisks(Integer legalEntityCode, String search, Integer orderColumn,
			String orderDirection, Integer page, Integer size) {
		
		
	    Session session = getSession();
		List<MaintResidualRisk> maintResidualRisks = null;
		
		DataTableResponse dataTableResponse=new DataTableResponse();

		StringBuilder queryString=new StringBuilder(
				
				
				        " SELECT "
						+" legal_entity_code , "
						+" minimun_per  , "
						+" maximum_per , "
						+" residual_risk_code   , "
						+" residual_risk_desc , "
						+" auth_rej_remarks , "
						 
						+ " (select concat(gp.value , '-' , gp.description) from general_parameter gp where"
				        + " gp.key_1='ENTITY_STATUS' and gp.key_2='ENTITY_STATUS' and gp.value=rsp.entity_status "
				        + " and gp.legal_entity_code=rsp.legal_entity_code ) as entity_status ,  "
				         
						+ " (select concat(gp.value , '-' , gp.description)"
						+ " from general_parameter gp where "
						+ " gp.key_1='STATUS' and gp.value=rsp.status "
						+ " and gp.legal_entity_code=rsp.legal_entity_code ) as status, "
 
						+ "(select concat(u.user_id , '-' ,u.first_name,' ',u.last_name )"
						+ " from user u where "
						+ " u.user_id=rsp.maker "
						+ " and u.legal_entity_code=rsp.legal_entity_code ) as maker ,  "
	 
						+" maker_timestamp    , "
						+" checker , "
						+" checker_timestamp  , "
						+" businessdate_timestamp  , "
						+" sysdate_timestamp  "
						+" ,risk_weightage_percentage "  // column added as Risk Weightage moved under Residual Risk Maint
 						+" FROM (   "
						+" SELECT * FROM maint_residual_risk  "
						+" WHERE legal_entity_code =:legal_entity_code and status !='D' "
						+" UNION ALL "
						+" SELECT * FROM maint_residual_risk_wrk WHERE legal_entity_code =:legal_entity_code "
						+ " and status !='D'  "
						+"  )  rsp  WHERE legal_entity_code=:legal_entity_code "
				
				);
		
		
		if(!BankAuditUtil.isEmptyString(search)){
			queryString=queryString.append(" and ( "
					+ " rsp.minimun_per like :search  "
					+ " or  rsp.maximum_per like :search  "
					+ " or  rsp.risk_weightage_percentage like :search  "
					+ " or  rsp.residual_risk_code like :search  "
					+ " or  rsp.residual_risk_desc like :search  "
					+ " or  rsp.maker like :search  "
	                + " or  rsp.status IN (SELECT value FROM general_parameter  WHERE key_1='STATUS' and  description LIKE :search ) "
                    + " or  rsp.maker IN ( "
	                + " select u.user_id "
		            + " from user u where "
	            	+ " (concat(u.first_name , ' ' , u.last_name) like :search  ) "
		            + " and u.legal_entity_code =:legal_entity_code ) "
                    + " or  rsp.entity_status IN (SELECT value FROM general_parameter  WHERE key_1='ENTITY_STATUS' and key_2='ENTITY_STATUS' and description LIKE :search ) "
					+ " ) ");
		}
/*		audit_type_code     
		minimun_per         
		maximum_per         
		residual_risk_code  
		residual_risk_desc  
		status              
		maker               */
		String[] columns={
				"rsp.residual_risk_code",
				"rsp.minimun_per",
				"rsp.maximum_per",
				"rsp.residual_risk_desc",
				"rsp.risk_weightage_percentage",
				"rsp.maker",
				"rsp.status",
				"rsp.entity_status"};
		
		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(STATUS,'DF','R','RM','U','M','A') ASC , minimun_per ASC  "); // The code modified to get the records in the order of Status on landing page, the sequence is  Draft, Reject, Unauth, Modify, Auth
		}else if(orderColumn!=null && !BankAuditUtil.isEmptyString(orderDirection)){
			queryString=queryString.append(" order by ").append(columns[orderColumn]).append(" ").append(orderDirection);
		}
		
		Query query=session.createSQLQuery(queryString.toString())
				.setResultTransformer(new ResultTransformer() {
					
					@Override
					public Object transformTuple(Object[] tuple, String[] aliases) {
						MaintResidualRisk  maintResidualRisk=null;
						if(tuple!=null){
							maintResidualRisk=new MaintResidualRisk();
							
							if(tuple[0]!=null){ maintResidualRisk.setLegalEntityCode(Integer.parseInt(tuple[0].toString())); }
							if(tuple[1]!=null){ maintResidualRisk.setMinimunPer(Double.parseDouble(tuple[1].toString())); }
							if(tuple[2]!=null){ maintResidualRisk.setMaximumPer(Double.parseDouble(tuple[2].toString())); }
							if(tuple[3]!=null){ maintResidualRisk.setResidualRiskCode(tuple[3].toString()); }
							if(tuple[4]!=null){ maintResidualRisk.setResidualRiskDesc(tuple[4].toString()); }
							if(tuple[5]!=null){ maintResidualRisk.setAuthRejRemarks(tuple[5].toString()); }
							if(tuple[6]!=null){ maintResidualRisk.setEntityStatus(tuple[6].toString()); }
							if(tuple[7]!=null){ maintResidualRisk.setStatus(tuple[7].toString()); }
							if(tuple[8]!=null){ maintResidualRisk.setMaker(tuple[8].toString()); }
							if(tuple[9]!=null){ maintResidualRisk.setMakerTimestamp((Date)tuple[9]); }
							if(tuple[10]!=null){ maintResidualRisk.setChecker(tuple[10].toString()); }
							if(tuple[11]!=null){ maintResidualRisk.setCheckerTimestamp((Date)tuple[11]); }
							if(tuple[12]!=null){ maintResidualRisk.setBusinessdateTimestamp((Date)tuple[12]); }
							if(tuple[13]!=null){ maintResidualRisk.setSysdateTimestamp((Date)tuple[13]); }
							if(tuple[14]!=null){ maintResidualRisk.setRiskWeightagePercentage(Integer.parseInt(tuple[14].toString())); }
						}
						return maintResidualRisk;
					}
					
					@Override
					public List transformList(List collection) {
						return collection;
					}
				}
						)
				.setParameter("legal_entity_code", legalEntityCode);
		
	
		
		if(!BankAuditUtil.isEmptyString(search)){
			query.setParameter("search", "%"+search+"%");
		}
		
		
		ScrollableResults resultScroll = query.scroll(ScrollMode.SCROLL_INSENSITIVE);
		if(resultScroll.first()&&resultScroll.scroll(page*size)){
			
			maintResidualRisks= new ArrayList<>();
			int i = 0;
			while (size > i++) {
				maintResidualRisks.add((MaintResidualRisk) resultScroll.get(0));
			    if (!resultScroll.next())
			        break;
			}
			dataTableResponse.setData(maintResidualRisks);
			resultScroll.last();
			if(size!=0){
				dataTableResponse.setRecordsFiltered((resultScroll.getRowNumber()+1l/size)+1);
				dataTableResponse.setRecordsTotal((resultScroll.getRowNumber()+1l/size)+1);
			}else{
				dataTableResponse.setError("page size zero");
				dataTableResponse.setData(Collections.EMPTY_LIST);
				dataTableResponse.setRecordsTotal(0l);
				dataTableResponse.setRecordsFiltered(0l);
			}
			
		}else{
			dataTableResponse.setError(null);
			dataTableResponse.setData(Collections.EMPTY_LIST);
			dataTableResponse.setRecordsTotal(0l);
			dataTableResponse.setRecordsFiltered(0l);
		}
		return dataTableResponse;

	
		
	}
	
	


	@Override
	public Boolean isMaintResidualRisk(Integer legalEntityCode) {
		Session session=getSession();
		Long count=(Long)session.createQuery(
				" select count(*) "
				+ " from MaintResidualRisk   "
				+ " where "
				+ " legalEntityCode =:legalEntityCode ")
		.setParameter("legalEntityCode", legalEntityCode).uniqueResult();
		
		Long count1=(Long)session.createQuery(
				" select count(*) "
				+ " from MaintResidualRiskWrk   "
				+ " where "
				+ " legalEntityCode =:legalEntityCode ")
		.setParameter("legalEntityCode", legalEntityCode).uniqueResult();
		Boolean flag;
		if((count1!=null && count1 >0)||(count!=null && count >0)){
			flag= true;
		}else {
			flag= false;
		}
	return flag;
	}

	@Override
	public void deleteMaintResidualRisks(Integer legalEntityCode, String statusUnauth) {

		
		Session session=getSession();
		if(!BankAuditConstant.STATUS_AUTH.equals(statusUnauth)){
			session.createQuery("delete from MaintResidualRiskWrk where legalEntityCode =:legalEntityCode   ")
				.setParameter("legalEntityCode", legalEntityCode).executeUpdate();
			
			
		}else {
			session.createQuery("delete from MaintResidualRisk where legalEntityCode =:legalEntityCode   ")
				.setParameter("legalEntityCode", legalEntityCode).executeUpdate();
		
		}
	
	}
	
	@Override
	public MaintResidualRisk getResidualRiskOnPercentage(Integer legalEntityCode, Integer riskScore) {

		Session session=getSession();
		MaintResidualRisk rskScrPcn =new MaintResidualRisk();
		System.out.println("LE.. "+legalEntityCode +" RS.. "+riskScore);
		try{
			rskScrPcn=(MaintResidualRisk)session.createQuery(
				 " from MaintResidualRisk  rp "
				+ " where "
				+ " rp.legalEntityCode =:legalEntityCode "
				+ " and (:riskScore > rp.minimunPer and :riskScore <= rp.maximumPer)")
				.setParameter("legalEntityCode", legalEntityCode)
				.setParameter("riskScore", riskScore).uniqueResult();
			System.out.println("rskScrPcn .... "+ rskScrPcn);
		}catch(Exception e) {
			e.printStackTrace(System.out);
		}return rskScrPcn;
	}

	@Override
	public Boolean isResidualRiskCode(Integer legalEntityCode, String residualRiskCode) {
		Session session=getSession();
		Long count=(Long)session.createQuery(
				" select count(*) "
				+ " from MaintResidualRisk   "
				+ " where "
				+ " legalEntityCode =:legalEntityCode "
				+ " and residualRiskCode =:residualRiskCode")
		.setParameter("legalEntityCode", legalEntityCode)
		.setParameter("residualRiskCode", residualRiskCode)
		.uniqueResult();
		
		Long count1=(Long)session.createQuery(
				" select count(*) "
				+ " from MaintResidualRiskWrk   "
				+ " where "
				+ " legalEntityCode =:legalEntityCode "
				+ " and residualRiskCode =:residualRiskCode")
		.setParameter("legalEntityCode", legalEntityCode)
		.setParameter("residualRiskCode", residualRiskCode).uniqueResult();
		Boolean flag;
		if((count1!=null && count1 >0)||(count!=null && count >0)){
			flag= true;
		}else {
			flag= false;
		}
	return flag;
	
	}
}
