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



@RestController

@RequestMapping("/api/maintControlDesignEffectiveness")
public class MaintControlDesignEffectivenessController {
	@Autowired
	MaintControlDesignEffectivenessService maintControlDesignEffectivenessService;
	
	@Autowired
	BusinessDateService businessDateService;
	
	static final Logger logger = Logger.getLogger(MaintControlDesignEffectivenessController.class);
	
	
@RequestMapping(method=RequestMethod.POST,consumes=MediaType.APPLICATION_JSON_VALUE,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus createMaintControlDesignEffectiveness(@RequestBody MaintControlDesignEffectiveness maintControlDesignEffectiveness){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(maintControlDesignEffectiveness!=null 
				&& !BankAuditUtil.isEmptyString(maintControlDesignEffectiveness.getControlDesignEffCode())
				&& !BankAuditUtil.isEmptyString(maintControlDesignEffectiveness.getControlDesignEffType())
				&& !BankAuditUtil.isEmptyString(maintControlDesignEffectiveness.getControlDesignEffDesc())
				){
			try {
				Boolean validateScore= maintControlDesignEffectivenessService.validateScore(maintControlDesignEffectiveness); // To validate the duplicate entry of the Score for the Criticality Type
				logger.info(" createMaintControlDesignEffectiveness validateScore:: "+ validateScore);
				if(!validateScore)
				{
					maintControlDesignEffectiveness.setBusinessdateTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(maintControlDesignEffectiveness.getLegalEntityCode()));
					maintControlDesignEffectiveness.setSysdateTimestamp(new Timestamp(System.currentTimeMillis()));
					maintControlDesignEffectiveness.setMakerTimestamp(maintControlDesignEffectiveness.getBusinessdateTimestamp());
					maintControlDesignEffectivenessService.createMaintControlDesignEffectiveness(maintControlDesignEffectiveness);
					serviceStatus.setStatus("success");
					serviceStatus.setMessage(" successfully created ");
				}else {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("The Score is already maintained for "+maintControlDesignEffectiveness.getControlDesignEffType()+ " 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 updateMaintControlDesignEffectiveness(@RequestBody MaintControlDesignEffectiveness maintControlDesignEffectiveness){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(maintControlDesignEffectiveness!=null 
				&& !BankAuditUtil.isEmptyString(maintControlDesignEffectiveness.getControlDesignEffCode())
				&& !BankAuditUtil.isEmptyString(maintControlDesignEffectiveness.getControlDesignEffType())
				&& !BankAuditUtil.isEmptyString(maintControlDesignEffectiveness.getControlDesignEffDesc())
				){
			
			try {
				logger.info("inside updateMaintControlDesignEffectiveness ....");
				Boolean validateScore = false;
				if(! "A".equals(maintControlDesignEffectiveness.getStatus())) // The condition to be validated for a New or Updated Record, there is no validation check during Authorization.
					validateScore= maintControlDesignEffectivenessService.validateScore(maintControlDesignEffectiveness); // To validate the duplicate entry of the Score for the Criticality Type
				logger.info(" updateMaintCriticality validateScore:: "+ validateScore);
				if(!validateScore)
				{
					maintControlDesignEffectiveness.setBusinessdateTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(maintControlDesignEffectiveness.getLegalEntityCode()));
					maintControlDesignEffectiveness.setSysdateTimestamp(new Timestamp(System.currentTimeMillis()));
					maintControlDesignEffectiveness.setMakerTimestamp(maintControlDesignEffectiveness.getBusinessdateTimestamp());
					maintControlDesignEffectivenessService.updateMaintControlDesignEffectiveness(maintControlDesignEffectiveness);
					serviceStatus.setStatus("success");
					serviceStatus.setMessage(" successfully updated ");
				}else {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("The Score is already maintained for "+maintControlDesignEffectiveness.getControlDesignEffType()+ " 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="/getControlDesignEffByCodeAndType/{legalEntityCode}/{controlDesignEffCode}/{controlDesignEffType}/{status}",method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus getControlDesignEffByCodeAndType(
			@PathVariable("controlDesignEffCode")String controlDesignEffCode,
			@PathVariable("controlDesignEffType")String controlDesignEffType,
			@PathVariable("legalEntityCode")String legalEntityCodeStr,
			@PathVariable("status")String status
			){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(!BankAuditUtil.isEmptyString(controlDesignEffCode)
				&& !BankAuditUtil.isEmptyString(controlDesignEffType)
				&& !BankAuditUtil.isEmptyString(legalEntityCodeStr)){
			try {
				
				
				Integer legalEntityCode=Integer.parseInt(legalEntityCodeStr);
				MaintControlDesignEffectiveness maintControlDesignEffectiveness=maintControlDesignEffectivenessService.getControlDesignEffByCodeAndType(legalEntityCode, controlDesignEffCode, controlDesignEffType, status);
				if(maintControlDesignEffectiveness!=null){
					serviceStatus.setResult(maintControlDesignEffectiveness);
					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="/getControlDesignEffectivenessByType/{legalEntityCode}/{controlDesignEffType}",method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus getControlDesignEffectivenessByType(
			@PathVariable("controlDesignEffType")String controlDesignEffType,
			@PathVariable("legalEntityCode")Integer legalEntityCode
			){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if( !BankAuditUtil.isEmptyString(controlDesignEffType)
				&& legalEntityCode!=null ){
			try {
				List<MaintControlDesignEffectiveness> maintControlDesignEffectivenesss=maintControlDesignEffectivenessService.getControlDesignEffectivenessByType(legalEntityCode ,controlDesignEffType);
				if(maintControlDesignEffectivenesss!=null && !maintControlDesignEffectivenesss.isEmpty()){
					serviceStatus.setResult(maintControlDesignEffectivenesss);
					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 getAllMaintControlDesignEffectiveness(
			@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 = maintControlDesignEffectivenessService.getAllMaintControlDesignEffectiveness(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="/isMaintControlDesignEffectiveness/{legalEntityCode}/{controlDesignEffCode}/{controlDesignEffType}",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus isMaintControlDesignEffectiveness(@PathVariable("legalEntityCode")Integer legalEntityCode,
			@PathVariable("controlDesignEffCode") String controlDesignEffCode,
			@PathVariable("controlDesignEffType") String controlDesignEffType
			){
		ServiceStatus serviceStatus=new ServiceStatus();
		if(legalEntityCode!=null 
				&& !BankAuditUtil.isEmptyString(controlDesignEffCode)
				&&  !BankAuditUtil.isEmptyString(controlDesignEffType)){
			
			try {
			    Boolean maintControlDesignEffectiveness=maintControlDesignEffectivenessService.isMaintControlDesignEffectiveness(legalEntityCode,controlDesignEffCode,controlDesignEffType);
		    	serviceStatus.setResult(maintControlDesignEffectiveness);
			    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 getMaintControlDesignEffectiveness(@RequestParam("legalEntityCode")String legalEntityCodeStr){
		ServiceStatus serviceStatus=new ServiceStatus();
		if(!BankAuditUtil.isEmptyString(legalEntityCodeStr)){
			try {
				logger.info("getMaintControlDesignEffectiveness .."+ legalEntityCodeStr);
				Integer legalEntityCode=Integer.parseInt(legalEntityCodeStr);
				List<MaintControlDesignEffectiveness> maintControlDesignEffectivenesses = maintControlDesignEffectivenessService.getMaintControlDesignEffectiveness(legalEntityCode);
				if(maintControlDesignEffectivenesses!=null && !maintControlDesignEffectivenesses.isEmpty()){
					serviceStatus.setStatus("success");
					serviceStatus.setMessage("successfuly retrieved");
					serviceStatus.setResult(maintControlDesignEffectivenesses);
				} 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;
	}
	
}
