package com.bankaudit.rest.controller;

import java.sql.Timestamp;
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.MaintHealthIndex;
import com.bankaudit.service.BusinessDateService;
import com.bankaudit.service.MaintHealthIndexService;
import com.bankaudit.util.BankAuditUtil;
import com.bankaudit.util.ServiceStatus;



@RestController

@RequestMapping("/api/maintHealthIndex")
public class MaintHealthIndexController {
	
	@Autowired
	MaintHealthIndexService maintHealthIndexService;
	
	/**
	 * 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(MaintHealthIndexController.class);
	
	/**
	 * This method is use to Creates the risk score percentage.
	 *
	 * @param maintHealthIndexs
	 *            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 createMaintHealthIndex(@RequestBody List<MaintHealthIndex> maintHealthIndexs){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(maintHealthIndexs!=null && !maintHealthIndexs.isEmpty()){
			try{
			
			int size = maintHealthIndexs.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(!maintHealthIndexs.get(j).getStatus().equalsIgnoreCase("D") && val != false){  // Skip status "D" records, as they are not considered for evaluation 
					int mino=maintHealthIndexs.get(j).getMinimunPer();
					int maxo=maintHealthIndexs.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=maintHealthIndexs.get(k).getMinimunPer();
						int maxi=maintHealthIndexs.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;
					maintHealthIndexs.get(j).setBusinessdateTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(maintHealthIndexs.get(j).getLegalEntityCode()));
					maintHealthIndexs.get(j).setSysdateTimestamp(new Timestamp(System.currentTimeMillis()));
					maintHealthIndexs.get(j).setMakerTimestamp(maintHealthIndexs.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){
			maintHealthIndexService.createMaintHealthIndex(maintHealthIndexs);
			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 maintHealthIndexs
	 *            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 updateMaintHealthIndex(@RequestBody List<MaintHealthIndex> maintHealthIndexs){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(maintHealthIndexs!=null
				&& !maintHealthIndexs.isEmpty()
				){
			
			try{
				
				int size = maintHealthIndexs.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(!maintHealthIndexs.get(j).getStatus().equalsIgnoreCase("D") && val != false){   // Skip status "D" records, as they are not considered for evaluation 
						int mino=maintHealthIndexs.get(j).getMinimunPer();
						int maxo=maintHealthIndexs.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=maintHealthIndexs.get(k).getMinimunPer();
								int maxi=maintHealthIndexs.get(k).getMaximumPer();
								
								if(!maintHealthIndexs.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;
							maintHealthIndexs.get(j).setBusinessdateTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(maintHealthIndexs.get(j).getLegalEntityCode()));
							maintHealthIndexs.get(j).setSysdateTimestamp(new Timestamp(System.currentTimeMillis()));
							
							if(maintHealthIndexs.get(j).getStatus().equals(BankAuditConstant.STATUS_AUTH)){
								maintHealthIndexs.get(j).setCheckerTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(maintHealthIndexs.get(j).getLegalEntityCode()));
							}else{
								maintHealthIndexs.get(j).setMakerTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(maintHealthIndexs.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){
				maintHealthIndexService.updateMaintHealthIndexs(maintHealthIndexs);
				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}/{healthIndexCode}/{status}",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus getMaintHealthIndex(@PathVariable("legalEntityCode")Integer legalEntityCode,
			@PathVariable("healthIndexCode") String healthIndexCode,
			@PathVariable("status") String status
			){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(legalEntityCode!=null 
				&& !BankAuditUtil.isEmptyString(healthIndexCode)){
			
			try {
			    MaintHealthIndex maintHealthIndex=maintHealthIndexService.getMaintHealthIndex(legalEntityCode,healthIndexCode,status);
			    if(maintHealthIndex!=null){
			    	serviceStatus.setResult(maintHealthIndex);
				    serviceStatus.setStatus("success");
				    serviceStatus.setMessage("successfully retrieved ");	
			    }else {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("MaintHealthIndex 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 getMaintHealthIndexs(
			@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 = maintHealthIndexService.getMaintHealthIndexs(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 getMaintHealthIndexforUpdate(@PathVariable("legalEntityCode")Integer legalEntityCode,
			@PathVariable("status") String status
			){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(legalEntityCode!=null ){
			
			try {
				System.out.println("Inside getMaintHealthIndexforUpdate ....."+ status +" :: "+status);
			    List<MaintHealthIndex> maintHealthIndexList=maintHealthIndexService.getMaintHealthIndexforUpdate(legalEntityCode, status);
			    if(maintHealthIndexList!=null){
			    	serviceStatus.setResult(maintHealthIndexList);
				    serviceStatus.setStatus("success");
				    serviceStatus.setMessage("successfully retrieved ");	
			    }else {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("MaintHealthIndex 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="/isMaintHealthIndex/{legalEntityCode}",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus isMaintHealthIndex(@PathVariable("legalEntityCode")Integer legalEntityCode
			){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(legalEntityCode!=null){
			
			try {
		    	serviceStatus.setResult(maintHealthIndexService.isMaintHealthIndex(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="/isHealthIndexCode",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus isHealthIndexCode(@RequestParam("legalEntityCode")Integer legalEntityCode,
			@RequestParam("healthIndexCode") String healthIndexCode
			){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(legalEntityCode!=null 
				&& !BankAuditUtil.isEmptyString(healthIndexCode)){
			
			try {
		    	serviceStatus.setResult(maintHealthIndexService.isHealthIndexCode(legalEntityCode,healthIndexCode));
			    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="/getHealthIndexOnPercentage/{legalEntityCode}/{riskScore}",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus getHealthIndexOnPercentage(@PathVariable("legalEntityCode")Integer legalEntityCode,
			@PathVariable("riskScore") Integer riskScore
			){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(legalEntityCode!=null && riskScore != null && !BankAuditUtil.isEmptyString(riskScore.toString()) ){
			
			try {
		    	serviceStatus.setResult(maintHealthIndexService.getHealthIndexOnPercentage(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;
	}

}
