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.dto.DataTableResponse;
import com.bankaudit.model.MaintProbabilityScale;
import com.bankaudit.service.BusinessDateService;
import com.bankaudit.service.MaintProbabilityScaleService;
import com.bankaudit.util.BankAuditUtil;
import com.bankaudit.util.ServiceStatus;



@RestController

@RequestMapping("/api/maintProbabilityScale")
public class MaintProbabilityScaleController {
	
	@Autowired
	MaintProbabilityScaleService maintProbabilityScaleService;
	
	@Autowired
	BusinessDateService businessDateService;
	
	static final Logger logger = Logger.getLogger(MaintProbabilityScaleController.class);
	
	
@RequestMapping(method=RequestMethod.POST,consumes=MediaType.APPLICATION_JSON_VALUE,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus createMaintProbabilityScale(@RequestBody MaintProbabilityScale maintProbabilityScale){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(maintProbabilityScale!=null 
				&& !BankAuditUtil.isEmptyString(maintProbabilityScale.getProbabltyScaleCode())
				&& !BankAuditUtil.isEmptyString(maintProbabilityScale.getProbabltyScaleType())
				&& !BankAuditUtil.isEmptyString(maintProbabilityScale.getProbabltyScaleDesc())
				){
			try {
				Boolean validateScore= maintProbabilityScaleService.validateScore(maintProbabilityScale); // To validate the duplicate entry of the Score for the Criticality Type
				logger.info(" createMaintProbabilityScale validateScore:: "+ validateScore);
				if(!validateScore)
				{
					maintProbabilityScale.setBusinessdateTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(maintProbabilityScale.getLegalEntityCode()));
					maintProbabilityScale.setSysdateTimestamp(new Timestamp(System.currentTimeMillis()));
					maintProbabilityScale.setMakerTimestamp(maintProbabilityScale.getBusinessdateTimestamp());
					maintProbabilityScaleService.createMaintProbabilityScale(maintProbabilityScale);
					serviceStatus.setStatus("success");
					serviceStatus.setMessage(" successfully created ");
				}else {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("The Score is already maintained for "+maintProbabilityScale.getProbabltyScaleType()+ " Probability Type.");
				}
			} 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(method=RequestMethod.PUT,consumes=MediaType.APPLICATION_JSON_VALUE,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus updateMaintProbabilityScale(@RequestBody MaintProbabilityScale maintProbabilityScale){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(maintProbabilityScale!=null 
				&& !BankAuditUtil.isEmptyString(maintProbabilityScale.getProbabltyScaleCode())
				&& !BankAuditUtil.isEmptyString(maintProbabilityScale.getProbabltyScaleType())
				&& !BankAuditUtil.isEmptyString(maintProbabilityScale.getProbabltyScaleDesc())
				){
			
			try {
				logger.info("inside updateMaintProbability ....");
				Boolean validateScore = false;
				if(! "A".equals(maintProbabilityScale.getStatus())) // The condition to be validated for a New or Updated Record, there is no validation check during Authorization.
					validateScore= maintProbabilityScaleService.validateScore(maintProbabilityScale); // To validate the duplicate entry of the Score for the Criticality Type
				logger.info(" updateMaintCriticality validateScore:: "+ validateScore);
				if(!validateScore)
				{
					maintProbabilityScale.setBusinessdateTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(maintProbabilityScale.getLegalEntityCode()));
					maintProbabilityScale.setSysdateTimestamp(new Timestamp(System.currentTimeMillis()));
					maintProbabilityScale.setMakerTimestamp(maintProbabilityScale.getBusinessdateTimestamp());
					maintProbabilityScaleService.updateMaintProbabilityScale(maintProbabilityScale);
					serviceStatus.setStatus("success");
					serviceStatus.setMessage(" successfully updated ");
				}else {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("The Score is already maintained for "+maintProbabilityScale.getProbabltyScaleType()+ " Criticality Type.");
				}
			} 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="/getProbabilityByProbabiltyCodeAndProbabilityOfType/{legalEntityCode}/{probabltyScaleCode}/{probabltyScaleType}/{status}",method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus getProbabilityByProbabiltyCodeAndProbabilityOfType(
			@PathVariable("probabltyScaleCode")String probabltyScaleCode,
			@PathVariable("probabltyScaleType")String probabltyScaleType,
			@PathVariable("legalEntityCode")String legalEntityCodeStr,
			@PathVariable("status")String status
			){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(!BankAuditUtil.isEmptyString(probabltyScaleCode)
				&& !BankAuditUtil.isEmptyString(probabltyScaleType)
				&& !BankAuditUtil.isEmptyString(legalEntityCodeStr)){
			try {
				
				
				Integer legalEntityCode=Integer.parseInt(legalEntityCodeStr);
				MaintProbabilityScale maintProbabilityScale=maintProbabilityScaleService.getProbabilityByProbabiltyCodeAndProbabilityOfType(legalEntityCode, probabltyScaleCode, probabltyScaleType, status);
				if(maintProbabilityScale!=null){
					serviceStatus.setResult(maintProbabilityScale);
					serviceStatus.setStatus("success");
					serviceStatus.setMessage("successfully retrieved");
				}else {
					serviceStatus.setMessage("codes not found ");
					serviceStatus.setStatus("failure");
				}
			} catch (Exception e) {
				e.printStackTrace();
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("failure");
			}
			
		}else {
			serviceStatus.setStatus("failure");
			serviceStatus.setMessage("invalid code");
		}
		return serviceStatus;
	}
	
	
@RequestMapping(value="/getProbabilityByProbabilityOfType/{legalEntityCode}/{probabltyScaleType}",method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus getProbabilityByProbabilityOfType(
			@PathVariable("probabltyScaleType")String probabltyScaleType,
			@PathVariable("legalEntityCode")Integer legalEntityCode
			){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if( !BankAuditUtil.isEmptyString(probabltyScaleType)
				&& legalEntityCode!=null ){
			try {
				List<MaintProbabilityScale> maintProbabilityScales=maintProbabilityScaleService.getProbabilityByProbabilityOfType(legalEntityCode ,probabltyScaleType);
				if(maintProbabilityScales!=null && !maintProbabilityScales.isEmpty()){
					serviceStatus.setResult(maintProbabilityScales);
					serviceStatus.setStatus("success");
					serviceStatus.setMessage("successfully retrieved");
				}else {
					serviceStatus.setMessage("codes not found ");
					serviceStatus.setStatus("failure");
				}
			} catch (Exception e) {
				e.printStackTrace();
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("failure");
			}
			
		}else {
			serviceStatus.setStatus("failure");
			serviceStatus.setMessage("invalid code");
		}
		return serviceStatus;
	}
	
	
@RequestMapping(value="/getAll",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE) 
	DataTableResponse getAllMaintProbabilityScale(
			@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 draw=Integer.parseInt(drawStr);
				Integer size=Integer.parseInt(length);
				Integer page=Integer.parseInt(start)/size;
				Integer orderColumn=null;
				Integer legalEntityCode=Integer.parseInt(legalEntityCodeStr);
				if(!BankAuditUtil.isEmptyString(orderColumnStr)){
					orderColumn=Integer.parseInt(orderColumnStr);
				}
				
				dataTableResponse = maintProbabilityScaleService.getAllMaintProbabilityScale(search,orderColumn,orderDirection,page,size,legalEntityCode);
				dataTableResponse.setDraw(draw);    
					
			} catch (Exception e) {
                dataTableResponse=new DataTableResponse();
                dataTableResponse.setError(e.getMessage());
				e.printStackTrace();
			}
		
		}else {
			dataTableResponse=new DataTableResponse();
			dataTableResponse.setError("invalid payload");
		}
		
		return dataTableResponse;
	}
	
	
@RequestMapping(value="/isMaintProbabilityScale/{legalEntityCode}/{probabilityCode}/{probabilityOfType}",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus isMaintProbabilityScale(@PathVariable("legalEntityCode")Integer legalEntityCode,
			@PathVariable("probabilityCode") String probabilityCode,
			@PathVariable("probabilityOfType") String probabilityOfType
			){
		ServiceStatus serviceStatus=new ServiceStatus();
		if(legalEntityCode!=null 
				&& !BankAuditUtil.isEmptyString(probabilityCode)
				&&  !BankAuditUtil.isEmptyString(probabilityOfType)){
			
			try {
			    Boolean maintProbabilityScale=maintProbabilityScaleService.isMaintProbabilityScale(legalEntityCode,probabilityCode,probabilityOfType);
		    	serviceStatus.setResult(maintProbabilityScale);
			    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="/getByLegalEntityCode",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE) 
	ServiceStatus getMaintProbabilityScale(@RequestParam("legalEntityCode")String legalEntityCodeStr){
		ServiceStatus serviceStatus=new ServiceStatus();
		if(!BankAuditUtil.isEmptyString(legalEntityCodeStr)){
			try {
				logger.info("getMaintProbabilityScale .."+ legalEntityCodeStr);
				Integer legalEntityCode=Integer.parseInt(legalEntityCodeStr);
				List<MaintProbabilityScale> maintProbabilityScales = maintProbabilityScaleService.getMaintProbabilityScale(legalEntityCode);
				if(maintProbabilityScales!=null && !maintProbabilityScales.isEmpty()){
					serviceStatus.setStatus("success");
					serviceStatus.setMessage("successfuly retrieved");
					serviceStatus.setResult(maintProbabilityScales);
				} else {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("no records found");
				}
			} catch (Exception e) {
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("failure");
				e.printStackTrace();
			}
		
		}else {
			serviceStatus.setStatus("failure");
			serviceStatus.setMessage("legalEntityCode required");
		}
		return serviceStatus;
	}
	
	
}
