package com.bankaudit.rest.controller;

import java.sql.Timestamp;
import java.util.Collections;
import java.util.List;

import org.jboss.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.bankaudit.constants.BankAuditConstant;
import com.bankaudit.dto.DataTableResponse;
import com.bankaudit.model.MaintInherentRisk;
import com.bankaudit.service.BusinessDateService;
import com.bankaudit.service.MaintInherentRiskService;
import com.bankaudit.util.BankAuditUtil;
import com.bankaudit.util.ServiceStatus;



@RestController

@RequestMapping("/api/maintInherentRisk")
public class MaintInherentRiskController {
	
	@Autowired
	MaintInherentRiskService maintInherentRiskService;
	
	/**
	 * The business date service is autowired and make methods available from
	 * service layer .
	 */
	@Autowired
	BusinessDateService businessDateService;
	
	/** The Constant logger is used to specify the . */
	@Autowired
	
	static final Logger logger = Logger.getLogger(MaintInherentRiskController.class);
	
	/**
	 * This method is use to Creates the risk score percentage.
	 *
	 * @param maintInherentRisks
	 *            specify the risk score percentages
	 * @return the service status class object with response status and payload
	 *         .
	 */
	
@RequestMapping(method=RequestMethod.POST,consumes=MediaType.APPLICATION_JSON_VALUE,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus createMaintInherentRisk(@RequestBody List<MaintInherentRisk> maintInherentRisks){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(maintInherentRisks!=null && !maintInherentRisks.isEmpty()){
			try{
			
			int size = maintInherentRisks.size();
			int allRangeCoveredVerify=0;  // to verify that all the numbers from 0 to 100 covered or not.
			boolean val =true, validation=true, rangeCovered =true;
			for(int j=0; j<size; j++){
				if(!maintInherentRisks.get(j).getStatus().equalsIgnoreCase("D") && val != false){  // Skip status "D" records, as they are not considered for evaluation 
					int mino=maintInherentRisks.get(j).getMinimunPer();
					int maxo=maintInherentRisks.get(j).getMaximumPer();
					allRangeCoveredVerify += maxo - mino;
					System.out.println(j +"====================== is -- :: MIN = " +mino  + " MAX = " +maxo + "RangeCovered ::"+ allRangeCoveredVerify); 
					if(mino < 0 || maxo > 100) {
						val = false; validation =false;
					}
					
					for(int k=j+1; k <size; k++){
						int mini=maintInherentRisks.get(k).getMinimunPer();
						int maxi=maintInherentRisks.get(k).getMaximumPer();
						
						System.out.println(j +" is :: MINi = " +mini  + " MAXi = " +maxi);
						if( ((mino < maxo) && (maxo <= mini) && (mini < maxi)) || ((mini < maxi) && (maxi <= mino) && (mino < maxo))) 
							System.out.println("mino maxo mini maxi :: "+ mino +" "+ maxo +" " + mini + " " + maxi);
						else {
							System.out.println("Validation failed ");
							val = false; validation =false;
							break;
						}
						
					}if(!val) break;
					maintInherentRisks.get(j).setBusinessdateTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(maintInherentRisks.get(j).getLegalEntityCode()));
					maintInherentRisks.get(j).setSysdateTimestamp(new Timestamp(System.currentTimeMillis()));
					maintInherentRisks.get(j).setMakerTimestamp(maintInherentRisks.get(j).getBusinessdateTimestamp());
				}
			}
			if(allRangeCoveredVerify != 100) { // This is to verify all the Range from 0 to 100 covered or not.
				val=false; rangeCovered =false;
			}
			System.out.println("allRangeCoveredVerify ::"+ allRangeCoveredVerify);
		
		if(val){
			maintInherentRiskService.createMaintInherentRisk(maintInherentRisks);
			serviceStatus.setStatus("success");
			serviceStatus.setMessage("successfully created");
		}else {
			serviceStatus.setStatus("failure");
			System.out.println("RangeCovered ::"+ rangeCovered +" validate:: "+validation);
			if(!validation)	serviceStatus.setMessage("Please provide the valid range ");
			else serviceStatus.setMessage("Please cover all the possible ranges from 0 to 100 ");
		}
			
		} catch (Exception e) {
			e.printStackTrace();
			serviceStatus.setStatus("failure");
			serviceStatus.setMessage("failure");
			if(e instanceof org.springframework.dao.DataIntegrityViolationException) {
				serviceStatus.setMessage("DATAINTGRTY_VIOLATION");
			}
		}

		}else {
			serviceStatus.setStatus("failure");
			serviceStatus.setMessage("invalid payload");
		}
		
		return serviceStatus;
	}
	
	/**
	 * This method is use to Update risk score percentage.
	 *
	 * @param maintInherentRisks
	 *            specify the risk score percentages
	 * @return the service status class object with response status and payload
	 *         .
	 */
	
@RequestMapping(method=RequestMethod.PUT,consumes=MediaType.APPLICATION_JSON_VALUE,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus updateMaintInherentRisk(@RequestBody List<MaintInherentRisk> maintInherentRisks){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(maintInherentRisks!=null
				&& !maintInherentRisks.isEmpty()
				){
			
			try{
				
				int size = maintInherentRisks.size();
				int allRangeCoveredVerify=0;  // to verify that all the numbers from 0 to 100 covered or not.
				boolean val =true, validation=true, rangeCovered =true;
				
				for(int j=0; j<size; j++){
					if(!maintInherentRisks.get(j).getStatus().equalsIgnoreCase("D") && val != false){   // Skip status "D" records, as they are not considered for evaluation 
						int mino=maintInherentRisks.get(j).getMinimunPer();
						int maxo=maintInherentRisks.get(j).getMaximumPer();
						allRangeCoveredVerify += maxo - mino;
						
						if(mino < 0 || maxo > 100) {
							val = false; validation =false;
						}
						
						System.out.println(j +"============== is :: MIN = " +mino  + " MAX = " +maxo);
						for(int k=j+1; k <size; k++){
								int mini=maintInherentRisks.get(k).getMinimunPer();
								int maxi=maintInherentRisks.get(k).getMaximumPer();
								
								if(!maintInherentRisks.get(k).getStatus().equalsIgnoreCase("D")){
									if( ((mino < maxo) && (maxo <= mini) && (mini < maxi)) || ((mini < maxi) && (maxi <= mino) && (mino < maxo))) 
										System.out.println("mino maxo mini maxi :: "+ mino +" "+ maxo +" " + mini + " " + maxi);
									else {
										System.out.println("Validation failed ");
										val = false;
										break;
									}
								}
								
							}if(!val) break;
							maintInherentRisks.get(j).setBusinessdateTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(maintInherentRisks.get(j).getLegalEntityCode()));
							maintInherentRisks.get(j).setSysdateTimestamp(new Timestamp(System.currentTimeMillis()));
							
							if(maintInherentRisks.get(j).getStatus().equals(BankAuditConstant.STATUS_AUTH)){
								maintInherentRisks.get(j).setCheckerTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(maintInherentRisks.get(j).getLegalEntityCode()));
							}else{
								maintInherentRisks.get(j).setMakerTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(maintInherentRisks.get(j).getLegalEntityCode()));
							}
						}
				}
				
				if(allRangeCoveredVerify != 100) { // This is to verify all the Range from 0 to 100 covered or not.
					val=false; rangeCovered =false;
				}
				System.out.println("RangeCovered ::"+ allRangeCoveredVerify);
		
			if(val){
				maintInherentRiskService.updateMaintInherentRisks(maintInherentRisks);
				serviceStatus.setStatus("success");
				serviceStatus.setMessage("successfully updated");
			}else {
				serviceStatus.setStatus("failure");
				if(!validation)	serviceStatus.setMessage("Please provide the valid range ");
				else serviceStatus.setMessage("Please cover all the possible ranges from 0 to 100 ");
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			serviceStatus.setStatus("failure");
			serviceStatus.setMessage("failure");
			if(e instanceof org.springframework.dao.DataIntegrityViolationException) {
				serviceStatus.setMessage("DATAINTGRTY_VIOLATION");
			}
		}

		}else {
			serviceStatus.setStatus("failure");
			serviceStatus.setMessage("invalid payload");
		}
		
		return serviceStatus;
	}
	
	
@RequestMapping(value="/getByLegalEntityCodeAndRiskCode/{legalEntityCode}/{inherentRiskCode}/{status}",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus getMaintInherentRisk(@PathVariable("legalEntityCode")Integer legalEntityCode,
			@PathVariable("inherentRiskCode") String inherentRiskCode,
			@PathVariable("status") String status
			){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(legalEntityCode!=null 
				&& !BankAuditUtil.isEmptyString(inherentRiskCode)){
			
			try {
			    MaintInherentRisk maintInherentRisk=maintInherentRiskService.getMaintInherentRisk(legalEntityCode,inherentRiskCode,status);
			    if(maintInherentRisk!=null){
			    	serviceStatus.setResult(maintInherentRisk);
				    serviceStatus.setStatus("success");
				    serviceStatus.setMessage("successfully retrieved ");	
			    }else {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("MaintInherentRisk not found");
				}
				
			} catch (Exception e) {
				e.printStackTrace();
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("failure");
			}
			
		}else {
			serviceStatus.setStatus("failure");
			serviceStatus.setMessage("invalid payload ");
		}
		
		return serviceStatus;
	}
	

	
	/**
	 * This method is use to Gets the risk score percentages.
	 *
	 * @param drawStr
	 *            specify the draw str
	 * @param length
	 *            specify the length
	 * @param start
	 *            specify the start
	 * @param search
	 *            specify the search
	 * @param orderColumnStr
	 *            specify the order column str
	 * @param orderDirection
	 *            specify the order direction
	 * @param legalEntityCodeStr
	 *            specify the legal entity code str
	 * @return the data table response class object with response status and
	 *         payload .
	 */
	
@RequestMapping(value="/getAll",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE) 
	DataTableResponse getMaintInherentRisks(
			@RequestParam("draw") String drawStr,
			@RequestParam("length") String length,
			@RequestParam("start") String start,
			@RequestParam("search[value]") String search,
			@RequestParam("order[0][column]") String orderColumnStr,
			@RequestParam("order[0][dir]")String orderDirection,
			@RequestParam("legalEntityCode")String legalEntityCodeStr){
		
		DataTableResponse dataTableResponse=null;
		
		if(!BankAuditUtil.isEmptyString(drawStr)
				&& !BankAuditUtil.isEmptyString(length)
				&& !BankAuditUtil.isEmptyString(start)
				&& !BankAuditUtil.isEmptyString(legalEntityCodeStr)){
			try {
				Integer legalEntityCode=Integer.parseInt(legalEntityCodeStr);
				Integer draw=Integer.parseInt(drawStr);
				Integer size=Integer.parseInt(length);
				Integer page=Integer.parseInt(start)/size;
				Integer orderColumn=null;
				if(!BankAuditUtil.isEmptyString(orderColumnStr)){
					orderColumn=Integer.parseInt(orderColumnStr);
				}
				dataTableResponse = maintInherentRiskService.getMaintInherentRisks(legalEntityCode,search,orderColumn,orderDirection,page,size);
				dataTableResponse.setDraw(draw);    
					
			} catch (Exception e) {
                dataTableResponse=new DataTableResponse();
                dataTableResponse.setError(e.getMessage());
				e.printStackTrace();
			}
		
		}else {
			dataTableResponse=new DataTableResponse();
			dataTableResponse.setError("invalid data");
		}
		
		return dataTableResponse;
	}
	
	
	/**
	 * This method is use to Gets the risk score percentagefor update.
	 *
	 * @param legalEntityCode
	 *            specify the legal entity code
	 * @param auditTypeCode
	 *            specify the audit type code
	 * @param status
	 *            specify the status
	 * @return the service status class object with response status and payload
	 *         .
	 */
	
@RequestMapping(value="/getByLegalEntityCode/{legalEntityCode}/{status}",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus getMaintInherentRiskforUpdate(@PathVariable("legalEntityCode")Integer legalEntityCode,
			@PathVariable("status") String status
			){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(legalEntityCode!=null ){
			
			try {
				System.out.println("Inside getMaintInherentRiskforUpdate ....."+ status +" :: "+status);
			    List<MaintInherentRisk> maintInherentRiskList=maintInherentRiskService.getMaintInherentRiskforUpdate(legalEntityCode, status);
			    if(maintInherentRiskList!=null){
			    	serviceStatus.setResult(maintInherentRiskList);
				    serviceStatus.setStatus("success");
				    serviceStatus.setMessage("successfully retrieved ");	
			    }else {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("MaintInherentRisk not found");
				}
				
			} catch (Exception e) {
				e.printStackTrace();
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("failure");
			}
			
		}else {
			serviceStatus.setStatus("failure");
			serviceStatus.setMessage("invalid payload ");
		}
		return serviceStatus;
	}


	/**
	 * This method is use to Checks if is risk score percentage.
	 *
	 * @param legalEntityCode
	 *            specify the legal entity code
	 * @param auditTypeCode
	 *            specify the audit type code
	 * @return the service status class object with response status and payload
	 *         .
	 */
	
@RequestMapping(value="/isMaintInherentRisk/{legalEntityCode}",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus isMaintInherentRisk(@PathVariable("legalEntityCode")Integer legalEntityCode
			){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(legalEntityCode!=null){
			
			try {
		    	serviceStatus.setResult(maintInherentRiskService.isMaintInherentRisk(legalEntityCode));
			    serviceStatus.setStatus("success");
			    serviceStatus.setMessage("successfully retrieved ");	
		    
				
			} catch (Exception e) {
				e.printStackTrace();
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("failure");
			}
			
		}else {
			serviceStatus.setStatus("failure");
			serviceStatus.setMessage("invalid payload ");
		}
		
		return serviceStatus;
	}

	
@RequestMapping(value="/isInherentRiskCode",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus isInherentRiskCode(@RequestParam("legalEntityCode")Integer legalEntityCode,
			@RequestParam("inherentRiskCode") String inherentRiskCode
			){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(legalEntityCode!=null 
				&& !BankAuditUtil.isEmptyString(inherentRiskCode)){
			
			try {
		    	serviceStatus.setResult(maintInherentRiskService.isInherentRiskCode(legalEntityCode,inherentRiskCode));
			    serviceStatus.setStatus("success");
			    serviceStatus.setMessage("successfully retrieved ");	
		    
				
			} catch (Exception e) {
				e.printStackTrace();
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("failure");
			}
			
		}else {
			serviceStatus.setStatus("failure");
			serviceStatus.setMessage("invalid payload ");
		}
		
		return serviceStatus;
	}
	
	
@RequestMapping(value="/getInherentRiskOnPercentage/{legalEntityCode}/{riskScore}",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus getInherentRiskOnPercentage(@PathVariable("legalEntityCode")Integer legalEntityCode,
			@PathVariable("riskScore") Integer riskScore
			){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(legalEntityCode!=null && riskScore != null && !BankAuditUtil.isEmptyString(riskScore.toString()) ){
			
			try {
		    	serviceStatus.setResult(maintInherentRiskService.getInherentRiskOnPercentage(legalEntityCode,riskScore));
			    serviceStatus.setStatus("success");
			    serviceStatus.setMessage("successfully retrieved ");	
		    
				
			} catch (Exception e) {
				e.printStackTrace();
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("failure");
			}
			
		}else {
			serviceStatus.setStatus("failure");
			serviceStatus.setMessage("invalid payload ");
		}
		
		return serviceStatus;
	}
}
