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



@RestController

@RequestMapping("/api/maintLossEvents")
public class MaintLossEventsController {
	@Autowired
	MaintLossEventsService maintLossEventsService;
	
	@Autowired
	BusinessDateService businessDateService;
	
	static final Logger logger = Logger.getLogger(MaintLossEventsController.class);
	
	
@RequestMapping(method=RequestMethod.POST,consumes=MediaType.APPLICATION_JSON_VALUE,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus createMaintLossEvents(@RequestBody MaintLossEvents maintLossEvents){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(maintLossEvents!=null 
				&& !BankAuditUtil.isEmptyString(maintLossEvents.getLossEventCode())
				&& !BankAuditUtil.isEmptyString(maintLossEvents.getLossEventType())
				&& !BankAuditUtil.isEmptyString(maintLossEvents.getLossEventDesc())
				){
			try {
				Boolean validateScore= false;
				// validateScore= maintLossEventsService.validateScore(maintLossEvents); // To validate the duplicate entry of the Score for the Criticality Type
				logger.info(" createMaintLossEvents validateScore:: "+ validateScore);
				if(!validateScore)
				{
					maintLossEvents.setBusinessdateTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(maintLossEvents.getLegalEntityCode()));
					maintLossEvents.setSysdateTimestamp(new Timestamp(System.currentTimeMillis()));
					maintLossEvents.setMakerTimestamp(maintLossEvents.getBusinessdateTimestamp());
					maintLossEventsService.createMaintLossEvents(maintLossEvents);
					serviceStatus.setStatus("success");
					serviceStatus.setMessage(" successfully created ");
				}else {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("The Score is already maintained for "+maintLossEvents.getLossEventType()+ " 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 updateMaintLossEvents(@RequestBody MaintLossEvents maintLossEvents){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(maintLossEvents!=null 
				&& !BankAuditUtil.isEmptyString(maintLossEvents.getLossEventCode())
				&& !BankAuditUtil.isEmptyString(maintLossEvents.getLossEventType())
				&& !BankAuditUtil.isEmptyString(maintLossEvents.getLossEventDesc())
				){
			
			try {
				logger.info("inside updateMaintProbability ....");
				Boolean validateScore = false;
				if(! "A".equals(maintLossEvents.getStatus())) // The condition to be validated for a New or Updated Record, there is no validation check during Authorization.
					//validateScore= maintLossEventsService.validateScore(maintLossEvents); // To validate the duplicate entry of the Score for the Criticality Type
				logger.info(" updateMaintCriticality validateScore:: "+ validateScore);
				if(!validateScore)
				{
					maintLossEvents.setBusinessdateTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(maintLossEvents.getLegalEntityCode()));
					maintLossEvents.setSysdateTimestamp(new Timestamp(System.currentTimeMillis()));
					maintLossEvents.setMakerTimestamp(maintLossEvents.getBusinessdateTimestamp());
					maintLossEventsService.updateMaintLossEvents(maintLossEvents);
					serviceStatus.setStatus("success");
					serviceStatus.setMessage(" successfully updated ");
				}else {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("The Score is already maintained for "+maintLossEvents.getLossEventType()+ " 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="/getLossEventsByCodeAndType/{legalEntityCode}/{LossEventCode}/{lossEventType}/{status}",method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus getLossEventsByCodeAndType(
			@PathVariable("LossEventCode")String LossEventCode,
			@PathVariable("lossEventType")String lossEventType,
			@PathVariable("legalEntityCode")String legalEntityCodeStr,
			@PathVariable("status")String status
			){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(!BankAuditUtil.isEmptyString(LossEventCode)
				&& !BankAuditUtil.isEmptyString(lossEventType)
				&& !BankAuditUtil.isEmptyString(legalEntityCodeStr)){
			try {
				
				
				Integer legalEntityCode=Integer.parseInt(legalEntityCodeStr);
				MaintLossEvents maintLossEvents=maintLossEventsService.getLossEventsByCodeAndType(legalEntityCode, LossEventCode, lossEventType, status);
				if(maintLossEvents!=null){
					serviceStatus.setResult(maintLossEvents);
					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="/getLossEventsByType/{legalEntityCode}/{lossEventType}",method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus getLossEventsByType(
			@PathVariable("lossEventType")String lossEventType,
			@PathVariable("legalEntityCode")Integer legalEntityCode
			){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if( !BankAuditUtil.isEmptyString(lossEventType)
				&& legalEntityCode!=null ){
			try {
				List<MaintLossEvents> maintLossEventss=maintLossEventsService.getLossEventsByType(legalEntityCode ,lossEventType);
				if(maintLossEventss!=null && !maintLossEventss.isEmpty()){
					serviceStatus.setResult(maintLossEventss);
					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 getAllMaintLossEvents(
			@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 = maintLossEventsService.getAllMaintLossEvents(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="/isMaintLossEvents/{legalEntityCode}/{probabilityCode}/{probabilityOfType}",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus isMaintLossEvents(@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 maintLossEvents=maintLossEventsService.isMaintLossEvents(legalEntityCode,probabilityCode,probabilityOfType);
		    	serviceStatus.setResult(maintLossEvents);
			    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;
	}
}
