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



@RestController

@RequestMapping("/api/maintRiskWeightage")
public class MaintRiskWeightageController {
	
	@Autowired
	MaintRiskWeightageService maintRiskWeightageService;
	
	@Autowired
	BusinessDateService businessDateService;
	
	static final Logger logger = Logger.getLogger(MaintRiskWeightageController.class);
	
	
@RequestMapping(method=RequestMethod.POST,consumes=MediaType.APPLICATION_JSON_VALUE,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus createMaintRiskWeightage(@RequestBody MaintRiskWeightage maintRiskWeightage){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(maintRiskWeightage!=null 
				&& !BankAuditUtil.isEmptyString(maintRiskWeightage.getRiskWeightageCode())
				&& !BankAuditUtil.isEmptyString(maintRiskWeightage.getRiskWeightageType())
				&& !BankAuditUtil.isEmptyString(maintRiskWeightage.getRiskWeightageDesc())
				){
			try {
				Boolean validateScore= maintRiskWeightageService.validateScore(maintRiskWeightage); // To validate the duplicate entry of the Score for the Criticality Type
				logger.info(" createMaintRiskWeightage validateScore:: "+ validateScore);
				if(!validateScore)
				{
					maintRiskWeightage.setBusinessdateTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(maintRiskWeightage.getLegalEntityCode()));
					maintRiskWeightage.setSysdateTimestamp(new Timestamp(System.currentTimeMillis()));
					maintRiskWeightage.setMakerTimestamp(maintRiskWeightage.getBusinessdateTimestamp());
					maintRiskWeightageService.createMaintRiskWeightage(maintRiskWeightage);
					serviceStatus.setStatus("success");
					serviceStatus.setMessage(" successfully created ");
				}else {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("The Score is already maintained for "+maintRiskWeightage.getRiskWeightageType()+ " Risk Weightage 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 updateMaintRiskWeightage(@RequestBody MaintRiskWeightage maintRiskWeightage){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(maintRiskWeightage!=null 
				&& !BankAuditUtil.isEmptyString(maintRiskWeightage.getRiskWeightageCode())
				&& !BankAuditUtil.isEmptyString(maintRiskWeightage.getRiskWeightageType())
				&& !BankAuditUtil.isEmptyString(maintRiskWeightage.getRiskWeightageDesc())
				){
			
			try {
				logger.info("inside updateMaintRiskWeightage ....");
				Boolean validateScore = false;
				if(! "A".equals(maintRiskWeightage.getStatus())) // The condition to be validated for a New or Updated Record, there is no validation check during Authorization.
					validateScore= maintRiskWeightageService.validateScore(maintRiskWeightage); // To validate the duplicate entry of the Score for the Criticality Type
				logger.info(" updateMaintCriticality validateScore:: "+ validateScore);
				if(!validateScore)
				{
					maintRiskWeightage.setBusinessdateTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(maintRiskWeightage.getLegalEntityCode()));
					maintRiskWeightage.setSysdateTimestamp(new Timestamp(System.currentTimeMillis()));
					maintRiskWeightage.setMakerTimestamp(maintRiskWeightage.getBusinessdateTimestamp());
					maintRiskWeightageService.updateMaintRiskWeightage(maintRiskWeightage);
					serviceStatus.setStatus("success");
					serviceStatus.setMessage(" successfully updated ");
				}else {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("The Score is already maintained for "+maintRiskWeightage.getRiskWeightageType()+ " Risk Weightage 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="/getRiskWeightageByCodeAndType/{legalEntityCode}/{riskWeightageCode}/{riskWeightageType}/{status}",method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus getRiskWeightageByCodeAndType(
			@PathVariable("riskWeightageCode")String riskWeightageCode,
			@PathVariable("riskWeightageType")String riskWeightageType,
			@PathVariable("legalEntityCode")String legalEntityCodeStr,
			@PathVariable("status")String status
			){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(!BankAuditUtil.isEmptyString(riskWeightageCode)
				&& !BankAuditUtil.isEmptyString(riskWeightageType)
				&& !BankAuditUtil.isEmptyString(legalEntityCodeStr)){
			try {
				
				
				Integer legalEntityCode=Integer.parseInt(legalEntityCodeStr);
				MaintRiskWeightage maintRiskWeightage=maintRiskWeightageService.getRiskWeightageByCodeAndType(legalEntityCode, riskWeightageCode, riskWeightageType, status);
				if(maintRiskWeightage!=null){
					serviceStatus.setResult(maintRiskWeightage);
					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="/getRiskWeightageByType/{legalEntityCode}/{riskWeightageType}",method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus getRiskWeightageByType(
			@PathVariable("riskWeightageType")String riskWeightageType,
			@PathVariable("legalEntityCode")Integer legalEntityCode
			){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if( !BankAuditUtil.isEmptyString(riskWeightageType)
				&& legalEntityCode!=null ){
			try {
				List<MaintRiskWeightage> maintRiskWeightages=maintRiskWeightageService.getRiskWeightageByType(legalEntityCode ,riskWeightageType);
				if(maintRiskWeightages!=null && !maintRiskWeightages.isEmpty()){
					serviceStatus.setResult(maintRiskWeightages);
					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 getAllMaintRiskWeightage(
			@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 = maintRiskWeightageService.getAllMaintRiskWeightage(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="/isMaintRiskWeightage/{legalEntityCode}/{riskWeightageCode}/{riskWeightageType}",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus isMaintRiskWeightage(@PathVariable("legalEntityCode")Integer legalEntityCode,
			@PathVariable("riskWeightageCode") String riskWeightageCode,
			@PathVariable("riskWeightageType") String riskWeightageType
			){
		ServiceStatus serviceStatus=new ServiceStatus();
		if(legalEntityCode!=null 
				&& !BankAuditUtil.isEmptyString(riskWeightageCode)
				&&  !BankAuditUtil.isEmptyString(riskWeightageType)){
			
			try {
			    Boolean maintRiskWeightage=maintRiskWeightageService.isMaintRiskWeightage(legalEntityCode,riskWeightageCode,riskWeightageType);
		    	serviceStatus.setResult(maintRiskWeightage);
			    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;
	}

}
