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



@RestController

@RequestMapping("/api/maintControlOperatingEffectiveness")
public class MaintControlOperatingEffectivenessController {
	
	@Autowired
	MaintControlOperatingEffectivenessService maintControlOperatingEffectivenessService;
	
	@Autowired
	BusinessDateService businessDateService;
	
	static final Logger logger = Logger.getLogger(MaintControlOperatingEffectivenessController.class);
	
	
@RequestMapping(method=RequestMethod.POST,consumes=MediaType.APPLICATION_JSON_VALUE,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus createMaintControlOperatingEffectiveness(@RequestBody MaintControlOperatingEffectiveness maintControlOperatingEffectiveness){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(maintControlOperatingEffectiveness!=null 
				&& !BankAuditUtil.isEmptyString(maintControlOperatingEffectiveness.getControlOperatingEffCode())
				&& !BankAuditUtil.isEmptyString(maintControlOperatingEffectiveness.getControlOperatingEffType())
				&& !BankAuditUtil.isEmptyString(maintControlOperatingEffectiveness.getControlOperatingEffDesc())
				){
			try {
				Boolean validateScore= maintControlOperatingEffectivenessService.validateScore(maintControlOperatingEffectiveness); // To validate the duplicate entry of the Score for the Criticality Type
				logger.info(" createMaintControlOperatingEffectiveness validateScore:: "+ validateScore);
				if(!validateScore)
				{
					maintControlOperatingEffectiveness.setBusinessdateTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(maintControlOperatingEffectiveness.getLegalEntityCode()));
					maintControlOperatingEffectiveness.setSysdateTimestamp(new Timestamp(System.currentTimeMillis()));
					maintControlOperatingEffectiveness.setMakerTimestamp(maintControlOperatingEffectiveness.getBusinessdateTimestamp());
					maintControlOperatingEffectivenessService.createMaintControlOperatingEffectiveness(maintControlOperatingEffectiveness);
					serviceStatus.setStatus("success");
					serviceStatus.setMessage(" successfully created ");
				}else {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("The Score is already maintained for "+maintControlOperatingEffectiveness.getControlOperatingEffType()+ " Control Eff 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 updateMaintControlOperatingEffectiveness(@RequestBody MaintControlOperatingEffectiveness maintControlOperatingEffectiveness){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(maintControlOperatingEffectiveness!=null 
				&& !BankAuditUtil.isEmptyString(maintControlOperatingEffectiveness.getControlOperatingEffCode())
				&& !BankAuditUtil.isEmptyString(maintControlOperatingEffectiveness.getControlOperatingEffType())
				&& !BankAuditUtil.isEmptyString(maintControlOperatingEffectiveness.getControlOperatingEffDesc())
				){
			
			try {
				logger.info("inside updateMaintControlOperatingEffectiveness ....");
				Boolean validateScore = false;
				if(! "A".equals(maintControlOperatingEffectiveness.getStatus())) // The condition to be validated for a New or Updated Record, there is no validation check during Authorization.
					validateScore= maintControlOperatingEffectivenessService.validateScore(maintControlOperatingEffectiveness); // To validate the duplicate entry of the Score for the Criticality Type
				logger.info(" updateMaintCriticality validateScore:: "+ validateScore);
				if(!validateScore)
				{
					maintControlOperatingEffectiveness.setBusinessdateTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(maintControlOperatingEffectiveness.getLegalEntityCode()));
					maintControlOperatingEffectiveness.setSysdateTimestamp(new Timestamp(System.currentTimeMillis()));
					maintControlOperatingEffectiveness.setMakerTimestamp(maintControlOperatingEffectiveness.getBusinessdateTimestamp());
					maintControlOperatingEffectivenessService.updateMaintControlOperatingEffectiveness(maintControlOperatingEffectiveness);
					serviceStatus.setStatus("success");
					serviceStatus.setMessage(" successfully updated ");
				}else {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("The Score is already maintained for "+maintControlOperatingEffectiveness.getControlOperatingEffType()+ " Control Design Effectiveness 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="/getControlOperatingEffByCodeAndType/{legalEntityCode}/{controlOperatingEffCode}/{controlOperatingEffType}/{status}",method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus getControlOperatingEffByCodeAndType(
			@PathVariable("controlOperatingEffCode")String controlOperatingEffCode,
			@PathVariable("controlOperatingEffType")String controlOperatingEffType,
			@PathVariable("legalEntityCode")String legalEntityCodeStr,
			@PathVariable("status")String status
			){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(!BankAuditUtil.isEmptyString(controlOperatingEffCode)
				&& !BankAuditUtil.isEmptyString(controlOperatingEffType)
				&& !BankAuditUtil.isEmptyString(legalEntityCodeStr)){
			try {
				
				
				Integer legalEntityCode=Integer.parseInt(legalEntityCodeStr);
				MaintControlOperatingEffectiveness maintControlOperatingEffectiveness=maintControlOperatingEffectivenessService.getControlOperatingEffByCodeAndType(legalEntityCode, controlOperatingEffCode, controlOperatingEffType, status);
				if(maintControlOperatingEffectiveness!=null){
					serviceStatus.setResult(maintControlOperatingEffectiveness);
					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="/getControlOperatingEffByType/{legalEntityCode}/{controlOperatingEffType}",method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus getControlOperatingEffByType(
			@PathVariable("controlOperatingEffType")String controlOperatingEffType,
			@PathVariable("legalEntityCode")Integer legalEntityCode
			){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if( !BankAuditUtil.isEmptyString(controlOperatingEffType)
				&& legalEntityCode!=null ){
			try {
				List<MaintControlOperatingEffectiveness> maintControlOperatingEffectivenesss=maintControlOperatingEffectivenessService.getControlOperatingEffByType(legalEntityCode ,controlOperatingEffType);
				if(maintControlOperatingEffectivenesss!=null && !maintControlOperatingEffectivenesss.isEmpty()){
					serviceStatus.setResult(maintControlOperatingEffectivenesss);
					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 getAllMaintControlOperatingEffectiveness(
			@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 = maintControlOperatingEffectivenessService.getAllMaintControlOperatingEffectiveness(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="/isMaintControlOperatingEff/{legalEntityCode}/{controlOperatingEffCode}/{controlOperatingEffType}",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus isMaintControlOperatingEff(@PathVariable("legalEntityCode")Integer legalEntityCode,
			@PathVariable("controlOperatingEffCode") String controlOperatingEffCode,
			@PathVariable("controlOperatingEffType") String controlOperatingEffType
			){
		ServiceStatus serviceStatus=new ServiceStatus();
		if(legalEntityCode!=null 
				&& !BankAuditUtil.isEmptyString(controlOperatingEffCode)
				&&  !BankAuditUtil.isEmptyString(controlOperatingEffType)){
			
			try {
			    Boolean maintControlOperatingEffectiveness=maintControlOperatingEffectivenessService.isMaintControlOperatingEffectiveness(legalEntityCode,controlOperatingEffCode,controlOperatingEffType);
		    	serviceStatus.setResult(maintControlOperatingEffectiveness);
			    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 getMaintControlOperatingEffectiveness(@RequestParam("legalEntityCode")String legalEntityCodeStr){
		ServiceStatus serviceStatus=new ServiceStatus();
		if(!BankAuditUtil.isEmptyString(legalEntityCodeStr)){
			try {
				logger.info("getMaintProbabilityScale .."+ legalEntityCodeStr);
				Integer legalEntityCode=Integer.parseInt(legalEntityCodeStr);
				List<MaintControlOperatingEffectiveness> maintControlOperatingEffectivenesses = maintControlOperatingEffectivenessService.getMaintControlOperatingEffectiveness(legalEntityCode);
				if(maintControlOperatingEffectivenesses!=null && !maintControlOperatingEffectivenesses.isEmpty()){
					serviceStatus.setStatus("success");
					serviceStatus.setMessage("successfuly retrieved");
					serviceStatus.setResult(maintControlOperatingEffectivenesses);
				} 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;
	}

}
