package com.bankaudit.rest.process.service;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jboss.logging.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.bankaudit.constants.BankAuditConstant;
import com.bankaudit.dto.DataTableResponse;
import com.bankaudit.dto.process.AuditRatingDto;
import com.bankaudit.process.model.AuditDocumentDetails;
import com.bankaudit.process.model.AuditSchedule;
import com.bankaudit.process.model.AuditScheduleWrkTmp;
import com.bankaudit.rest.process.dao.AuditRatingDao;
import com.bankaudit.service.BusinessDateService;
import com.bankaudit.util.BankAuditUtil;

@Service("auditRatingService")
@Transactional("transactionManager")
public class AuditRatingServiceImpl implements AuditRatingService{
	
	@Autowired
	AuditRatingDao auditRatingDao;
	
	@Autowired
	BusinessDateService businessDateService;
	
	static final Logger logger = Logger.getLogger(AuditRatingServiceImpl.class);
	
	@Override
	public DataTableResponse getAuditRatingList(int legalEntityCode, String userId, String unitCode, String role, String search, Integer orderColumn,
			String orderDirection, Integer page, Integer size, String documentType, String documentSubType, LocalDate financialYear, String auditTypeCode) {
		List<LocalDate>  financialYearStrtEndList=null;
		if(financialYear!=null) financialYearStrtEndList= BankAuditUtil.getFinancialStartEndDatesNxtFrom(financialYear);
		DataTableResponse ds=auditRatingDao.getAuditRatingList(legalEntityCode,userId,unitCode,role,search,orderColumn,
				orderDirection, page, size, documentType, documentSubType, financialYear, auditTypeCode, financialYearStrtEndList);
		return ds;
	}
	
	@Override
	public AuditRatingDto getAuditByPlanIdAndAuditIdAndStatus(int legalEntityCode, String auditTypeCode, String planId,
			String auditId, String status, String role) {
		AuditRatingDto auditDtls=auditRatingDao.getAuditByPlanIdAndAuditIdAndStatus(legalEntityCode,auditTypeCode,planId,auditId,status,role); 
		 return auditDtls; 
	}
	
	
	@Override
	public String updateAuditScheduleComplianceRating(AuditRatingDto auditRatingDto) {
		try{						
			AuditSchedule auditSchedule =  auditRatingDto.getAuditSchedule();
			String role = auditRatingDto.getRole();
			//
			AuditScheduleWrkTmp auditScheduleWrkTmp =   new AuditScheduleWrkTmp();
			
			if(role.equalsIgnoreCase("G2") || role.equalsIgnoreCase("G8") ){
				 
				AuditSchedule auditScheduleA = (AuditSchedule) auditRatingDao.getAuditByAuditId(auditSchedule.getLegalEntityCode() , auditRatingDto.getAuditId() );
				BeanUtils.copyProperties(auditScheduleA, auditScheduleWrkTmp);
				
				auditScheduleWrkTmp.setRatingStatus(auditSchedule.getRatingStatus());				
				auditScheduleWrkTmp.setOnsiteComplianceRating(auditSchedule.getOnsiteComplianceRating());
				auditScheduleWrkTmp.setOnsiteComplianceScore(auditSchedule.getOnsiteComplianceScore());
				auditScheduleWrkTmp.setRatingMaker(auditSchedule.getRatingMaker());  
			}else{
				BeanUtils.copyProperties(auditSchedule, auditScheduleWrkTmp);
				auditScheduleWrkTmp.setDeskComplianceRating(auditSchedule.getDeskComplianceRating());
				auditScheduleWrkTmp.setDeskComplianceScore(auditSchedule.getDeskComplianceScore());
			}
			
			if(!auditScheduleWrkTmp.getRatingStatus().equalsIgnoreCase(BankAuditConstant.STATUS_AUTH)){
				
				auditScheduleWrkTmp.setRatingMakerTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(auditScheduleWrkTmp.getLegalEntityCode()));					 
				auditRatingDao.saveOrUpdate(auditScheduleWrkTmp);
				
				//Update Audit Rating document details if Reject or modified	
				auditRatingDao.authorizeAuditRatingDocuments(auditRatingDto);
				/*auditRatingDao.authorizeAuditRatingDocuments(auditScheduleWrkTmp.getLegalEntityCode(), auditScheduleWrkTmp.getAuditTypeCode(), auditScheduleWrkTmp.getAuditId(), 
						auditScheduleWrkTmp.getPlanId(), auditScheduleWrkTmp.getRatingChecker(),
						auditScheduleWrkTmp.getRatingStatus(), auditScheduleWrkTmp.getRatingAuthRejRemarks(),
						auditScheduleWrkTmp.getDocumentType(), auditScheduleWrkTmp.getDocumentSubType(),  role);*/
				
				
				 
			}
			else {
				
				//Update Rating for Compliance rating - AuditSchedule
				auditRatingDao.updateAuditScheduleRatingIfAuthorized(auditRatingDto);
				
				//Delete from AuditScheduleWrkTmp 					 
				auditRatingDao.DeleteAuditScheduleWrkTmpRatingIfAuthorized(auditScheduleWrkTmp);	
				
				//Update Audit Rating document details if Authorized
				auditRatingDao.authorizeAuditRatingDocuments(auditRatingDto);
				/*auditRatingDao.authorizeAuditRatingDocuments(auditScheduleWrkTmp.getLegalEntityCode(), auditScheduleWrkTmp.getAuditTypeCode(), auditScheduleWrkTmp.getAuditId(), 
						auditScheduleWrkTmp.getPlanId(), auditScheduleWrkTmp.getRatingChecker(),
						auditScheduleWrkTmp.getRatingStatus(), auditScheduleWrkTmp.getRatingAuthRejRemarks(),
						auditScheduleWrkTmp.getDocumentType(), auditScheduleWrkTmp.getDocumentSubType(), role);*/
			}
		}catch(Exception ex){
			logger.error("Error .." + ex.getMessage()+" :: "+ex.getCause());
			return BankAuditConstant.FAILED;
		}
		return BankAuditConstant.SUCCESS;
	}
	
	/*********** Document uploadDownload Start **********************/
	
	/*@Override
	public String getReferencePathById(Integer legalEntityCode, Integer id,  String status){
		return auditRatingDao.getReferencePathById(legalEntityCode, id, status);
	}*/
	
	
	@Override
	public Map<String, Integer>  uploadDocuments(Integer legalEntityCode, String auditTypeCode, String auditId, String planId,  String documentType,  String documentName,
			String maker, String userRoleId, CommonsMultipartFile[] files, String documentSubType)  { 
		 
		Map<String , Integer> uplodedIds = new HashMap<String , Integer>();	
			
			String referencePath="";		
			for (CommonsMultipartFile commonsMultipartFile : files) {
				Integer uploadId=0;
				try{
					
					AuditDocumentDetails auditRatingDocumentDetails = new AuditDocumentDetails(); 
					
					String pattern = "yyyyMMddHHmmssSSS";
		    		SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
		    		String fileNameAppender =legalEntityCode.toString()+auditTypeCode+documentType;
		    		referencePath=BankAuditUtil.uploadMaterial(commonsMultipartFile, BankAuditConstant.DIR_DOC_UPLOAD, simpleDateFormat.format(new Date())+"_"+fileNameAppender);
		    		
		    		auditRatingDocumentDetails.setLegalEntityCode(legalEntityCode);
		    		auditRatingDocumentDetails.setFileName(commonsMultipartFile.getOriginalFilename());
		    		auditRatingDocumentDetails.setReferencePath(referencePath);
		    		auditRatingDocumentDetails.setAuditTypeCode(auditTypeCode);
		    		auditRatingDocumentDetails.setAuditId(auditId);
		    		auditRatingDocumentDetails.setPlanId(planId);
		    		auditRatingDocumentDetails.setDocumentType(documentType);
		    		auditRatingDocumentDetails.setDocumentSubType(documentSubType);
		    		auditRatingDocumentDetails.setDocumentName(documentName);
		    		auditRatingDocumentDetails.setMaker(maker);
		    		auditRatingDocumentDetails.setBusinessdateTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(legalEntityCode));
		    		auditRatingDocumentDetails.setMakerTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(legalEntityCode));		    		
		    		auditRatingDocumentDetails.setStatus(BankAuditConstant.STATUS_AUTH);
		    		auditRatingDocumentDetails.setEntityStatus(BankAuditConstant.STATUS_AUTH);
 
		    		auditRatingDao.flushSession();
		    		auditRatingDao.saveOrUpdate(auditRatingDocumentDetails);
		    		uploadId = auditRatingDocumentDetails.getId();	    		
		    		 
				}catch (Exception e) {
					logger.error("Error .." + e.getMessage()+" :: "+e.getCause());
				}
				uplodedIds.put(commonsMultipartFile.getOriginalFilename(), uploadId);	
	       }			
			
		  //update maker
			auditRatingDao.flushSession();
			//auditRatingDao.updateMakerToWrkAndMaster(legalEntityCode, auditTypeCode, auditId, planId, maker, documentType, documentSubType);
			
		return uplodedIds;
	}

	@Override
	public String deleteAllAuditRatingDocumentsFromUI(Integer legalEntityCode, String auditTypeCode,  String auditId, String planId,   
			String status, String documentType,  String documentSubType){
		return auditRatingDao.deleteAllAuditRatingDocumentsFromUI(legalEntityCode, auditTypeCode, auditId, planId,  status, documentType, documentSubType);
	}
	
	@Override
	public String deleteAuditRatingDocumentsFromUI(Integer legalEntityCode,Integer id, String auditTypeCode, String auditId, String planId, String  status, String entityStatus,
			String documentType, String documentSubType){
		return auditRatingDao.deleteAuditRatingDocumentsFromUI(legalEntityCode, id, auditTypeCode, auditId, planId, status, entityStatus,
				  documentType,   documentSubType);
	}
	
	/*@Override
	public   List<Object> getAuditRatingDocumentDetails(Integer legalEntityCode, String auditTypeCode, String auditId, String planId, 
				String documentType, String userId, String userRoleId, String status, String documentSubType){
		return auditRatingDao.getAuditRatingDocumentDetails(legalEntityCode, auditTypeCode, auditId, planId, documentType, userId, userRoleId, status, documentSubType);
	  }*/
	/*********** Document upload Download End **********************/
	
	@Override
	public String getOnsiteComplianceStatus(int legalEntityCode,String auditTypeCode, String planId,String auditId){
		return auditRatingDao.getOnsiteComplianceStatus(legalEntityCode, auditTypeCode, planId, auditId);
	}
	

	@Override
	public  void deleteOnsiteComplianceDataFromWrkTmp(int legalEntityCode,String auditTypeCode, String planId,String auditId){
		auditRatingDao.deleteOnsiteComplianceDataFromWrkTmp(legalEntityCode, auditTypeCode, planId, auditId);
	 }
}
