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.MaintControlClssfcBucket;
import com.bankaudit.service.BusinessDateService;
import com.bankaudit.service.MaintControlClssfcBucketService;
import com.bankaudit.util.BankAuditUtil;
import com.bankaudit.util.ServiceStatus;



@RestController

@RequestMapping("/api/maintControlClssfcBucket")
public class MaintControlClssfcBucketController {
	
	@Autowired
	MaintControlClssfcBucketService maintControlClssfcBucketService;
	
	@Autowired
	BusinessDateService businessDateService;
	
	static final Logger logger = Logger.getLogger(MaintControlClssfcBucketController.class);
	
	
@RequestMapping(method=RequestMethod.POST,consumes=MediaType.APPLICATION_JSON_VALUE,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus createMaintControlClssfcBucket(@RequestBody List<MaintControlClssfcBucket> maintControlClssfcBuckets){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(maintControlClssfcBuckets!=null && !maintControlClssfcBuckets.isEmpty()){
			try{
			
			int size = maintControlClssfcBuckets.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(!maintControlClssfcBuckets.get(j).getStatus().equalsIgnoreCase("D") && val != false){  // Skip status "D" records, as they are not considered for evaluation 
					int mino=maintControlClssfcBuckets.get(j).getMinimunPer();
					int maxo=maintControlClssfcBuckets.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=maintControlClssfcBuckets.get(k).getMinimunPer();
						int maxi=maintControlClssfcBuckets.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;
					maintControlClssfcBuckets.get(j).setBusinessdateTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(maintControlClssfcBuckets.get(j).getLegalEntityCode()));
					maintControlClssfcBuckets.get(j).setSysdateTimestamp(new Timestamp(System.currentTimeMillis()));
					maintControlClssfcBuckets.get(j).setMakerTimestamp(maintControlClssfcBuckets.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){
			maintControlClssfcBucketService.createMaintControlClssfcBucket(maintControlClssfcBuckets);
			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 maintControlClssfcBuckets
	 *            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 updateMaintControlClssfcBucket(@RequestBody List<MaintControlClssfcBucket> maintControlClssfcBuckets){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(maintControlClssfcBuckets!=null
				&& !maintControlClssfcBuckets.isEmpty()
				){
			
			try{
				
				int size = maintControlClssfcBuckets.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(!maintControlClssfcBuckets.get(j).getStatus().equalsIgnoreCase("D") && val != false){   // Skip status "D" records, as they are not considered for evaluation 
						int mino=maintControlClssfcBuckets.get(j).getMinimunPer();
						int maxo=maintControlClssfcBuckets.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=maintControlClssfcBuckets.get(k).getMinimunPer();
								int maxi=maintControlClssfcBuckets.get(k).getMaximumPer();
								
								if(!maintControlClssfcBuckets.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;
							maintControlClssfcBuckets.get(j).setBusinessdateTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(maintControlClssfcBuckets.get(j).getLegalEntityCode()));
							maintControlClssfcBuckets.get(j).setSysdateTimestamp(new Timestamp(System.currentTimeMillis()));
							
							if(maintControlClssfcBuckets.get(j).getStatus().equals(BankAuditConstant.STATUS_AUTH)){
								maintControlClssfcBuckets.get(j).setCheckerTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(maintControlClssfcBuckets.get(j).getLegalEntityCode()));
							}else{
								maintControlClssfcBuckets.get(j).setMakerTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(maintControlClssfcBuckets.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){
				maintControlClssfcBucketService.updateMaintControlClssfcBuckets(maintControlClssfcBuckets);
				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}/{controlClssfcBucketCode}/{status}",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus getMaintControlClssfcBucket(@PathVariable("legalEntityCode")Integer legalEntityCode,
			@PathVariable("controlClssfcBucketCode") String controlClssfcBucketCode,
			@PathVariable("status") String status
			){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(legalEntityCode!=null 
				&& !BankAuditUtil.isEmptyString(controlClssfcBucketCode)){
			
			try {
			    MaintControlClssfcBucket maintControlClssfcBucket=maintControlClssfcBucketService.getMaintControlClssfcBucket(legalEntityCode,controlClssfcBucketCode,status);
			    if(maintControlClssfcBucket!=null){
			    	serviceStatus.setResult(maintControlClssfcBucket);
				    serviceStatus.setStatus("success");
				    serviceStatus.setMessage("successfully retrieved ");	
			    }else {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("MaintControlClssfcBucket 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 getMaintControlClssfcBuckets(
			@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 = maintControlClssfcBucketService.getMaintControlClssfcBuckets(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 getMaintControlClssfcBucketforUpdate(@PathVariable("legalEntityCode")Integer legalEntityCode,
			@PathVariable("status") String status
			){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(legalEntityCode!=null ){
			
			try {
				System.out.println("Inside getMaintControlClssfcBucketforUpdate ....."+ status +" :: "+status);
			    List<MaintControlClssfcBucket> maintControlClssfcBucketList=maintControlClssfcBucketService.getMaintControlClssfcBucketforUpdate(legalEntityCode, status);
			    if(maintControlClssfcBucketList!=null){
			    	serviceStatus.setResult(maintControlClssfcBucketList);
				    serviceStatus.setStatus("success");
				    serviceStatus.setMessage("successfully retrieved ");	
			    }else {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("MaintControlClssfcBucket 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="/isMaintControlClssfcBucket/{legalEntityCode}",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus isMaintControlClssfcBucket(@PathVariable("legalEntityCode")Integer legalEntityCode
			){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(legalEntityCode!=null){
			
			try {
		    	serviceStatus.setResult(maintControlClssfcBucketService.isMaintControlClssfcBucket(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="/isControlClssfcBucketCode",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus isControlClssfcBucketCode(@RequestParam("legalEntityCode")Integer legalEntityCode,
			@RequestParam("controlClssfcBucketCode") String controlClssfcBucketCode
			){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(legalEntityCode!=null 
				&& !BankAuditUtil.isEmptyString(controlClssfcBucketCode)){
			
			try {
		    	serviceStatus.setResult(maintControlClssfcBucketService.isControlClssfcBucketCode(legalEntityCode,controlClssfcBucketCode));
			    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="/getControlClssfcBucketOnPercentage/{legalEntityCode}/{riskScore}",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus getControlClssfcBucketOnPercentage(@PathVariable("legalEntityCode")Integer legalEntityCode,
			@PathVariable("riskScore") Integer riskScore
			){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(legalEntityCode!=null && riskScore != null && !BankAuditUtil.isEmptyString(riskScore.toString()) ){
			
			try {
		    	serviceStatus.setResult(maintControlClssfcBucketService.getControlClssfcBucketOnPercentage(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;
	}

}
