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.model.MaintSeverityScale;
import com.bankaudit.service.BusinessDateService;
import com.bankaudit.service.MaintSeverityScaleService;
import com.bankaudit.util.BankAuditUtil;
import com.bankaudit.util.ServiceStatus;



@RestController

@RequestMapping("/api/maintSeverityScale")
public class MaintSeverityScaleController {
	@Autowired
	MaintSeverityScaleService maintSeverityScaleService;
	
	@Autowired
	BusinessDateService businessDateService;
	
	static final Logger logger = Logger.getLogger(MaintSeverityScaleController.class);
	
	
@RequestMapping(method=RequestMethod.POST,consumes=MediaType.APPLICATION_JSON_VALUE,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus createMaintSeverityScale(@RequestBody MaintSeverityScale maintSeverityScale){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(maintSeverityScale!=null 
				&& !BankAuditUtil.isEmptyString(maintSeverityScale.getSeverityScaleCode())
				&& !BankAuditUtil.isEmptyString(maintSeverityScale.getSeverityScaleType())
				&& !BankAuditUtil.isEmptyString(maintSeverityScale.getSeverityScaleDesc())
				){
			try {
				Boolean validateScore= maintSeverityScaleService.validateScore(maintSeverityScale); // To validate the duplicate entry of the Score for the Criticality Type
				logger.info(" createMaintSeverityScale validateScore:: "+ validateScore);
				if(!validateScore)
				{
					maintSeverityScale.setBusinessdateTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(maintSeverityScale.getLegalEntityCode()));
					maintSeverityScale.setSysdateTimestamp(new Timestamp(System.currentTimeMillis()));
					maintSeverityScale.setMakerTimestamp(maintSeverityScale.getBusinessdateTimestamp());
					maintSeverityScaleService.createMaintSeverityScale(maintSeverityScale);
					serviceStatus.setStatus("success");
					serviceStatus.setMessage(" successfully created ");
				}else {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("The Score is already maintained for "+maintSeverityScale.getSeverityScaleType()+ " Severity 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 updateMaintSeverityScale(@RequestBody MaintSeverityScale maintSeverityScale){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(maintSeverityScale!=null 
				&& !BankAuditUtil.isEmptyString(maintSeverityScale.getSeverityScaleCode())
				&& !BankAuditUtil.isEmptyString(maintSeverityScale.getSeverityScaleType())
				&& !BankAuditUtil.isEmptyString(maintSeverityScale.getSeverityScaleDesc())
				){
			
			try {
				logger.info("inside updateMaintSeverity ....");
				Boolean validateScore = false;
				if(! "A".equals(maintSeverityScale.getStatus())) // The condition to be validated for a New or Updated Record, there is no validation check during Authorization.
					validateScore= maintSeverityScaleService.validateScore(maintSeverityScale); // To validate the duplicate entry of the Score for the Criticality Type
				logger.info(" updateMaintCriticality validateScore:: "+ validateScore);
				if(!validateScore)
				{
					maintSeverityScale.setBusinessdateTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(maintSeverityScale.getLegalEntityCode()));
					maintSeverityScale.setSysdateTimestamp(new Timestamp(System.currentTimeMillis()));
					maintSeverityScale.setMakerTimestamp(maintSeverityScale.getBusinessdateTimestamp());
					maintSeverityScaleService.updateMaintSeverityScale(maintSeverityScale);
					serviceStatus.setStatus("success");
					serviceStatus.setMessage(" successfully updated ");
				}else {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("The Score is already maintained for "+maintSeverityScale.getSeverityScaleType()+ " 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="/getSeverityBySeverityCodeAndSeverityOfType/{legalEntityCode}/{severityScaleCode}/{severityScaleType}/{status}",method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus getSeverityBySeverityCodeAndSeverityOfType(
			@PathVariable("severityScaleCode")String severityScaleCode,
			@PathVariable("severityScaleType")String severityScaleType,
			@PathVariable("legalEntityCode")String legalEntityCodeStr,
			@PathVariable("status")String status
			){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(!BankAuditUtil.isEmptyString(severityScaleCode)
				&& !BankAuditUtil.isEmptyString(severityScaleType)
				&& !BankAuditUtil.isEmptyString(legalEntityCodeStr)){
			try {
				
				
				Integer legalEntityCode=Integer.parseInt(legalEntityCodeStr);
				MaintSeverityScale maintSeverityScale=maintSeverityScaleService.getSeverityBySeverityCodeAndSeverityOfType(legalEntityCode, severityScaleCode, severityScaleType, status);
				if(maintSeverityScale!=null){
					serviceStatus.setResult(maintSeverityScale);
					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="/getSeverityBySeverityOfType/{legalEntityCode}/{severityScaleType}",method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus getSeverityBySeverityOfType(
			@PathVariable("severityScaleType")String severityScaleType,
			@PathVariable("legalEntityCode")Integer legalEntityCode
			){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if( !BankAuditUtil.isEmptyString(severityScaleType)
				&& legalEntityCode!=null ){
			try {
				List<MaintSeverityScale> maintSeverityScales=maintSeverityScaleService.getSeverityBySeverityOfType(legalEntityCode ,severityScaleType);
				if(maintSeverityScales!=null && !maintSeverityScales.isEmpty()){
					serviceStatus.setResult(maintSeverityScales);
					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 getAllMaintSeverityScale(
			@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 = maintSeverityScaleService.getAllMaintSeverityScale(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="/isMaintSeverityScale/{legalEntityCode}/{severityScaleCode}/{severityScaleType}",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus isMaintSeverityScale(@PathVariable("legalEntityCode")Integer legalEntityCode,
			@PathVariable("severityScaleCode") String severityScaleCode,
			@PathVariable("severityScaleType") String severityScaleType
			){
		ServiceStatus serviceStatus=new ServiceStatus();
		if(legalEntityCode!=null 
				&& !BankAuditUtil.isEmptyString(severityScaleCode)
				&&  !BankAuditUtil.isEmptyString(severityScaleType)){
			
			try {
			    Boolean maintSeverityScale=maintSeverityScaleService.isMaintSeverityScale(legalEntityCode,severityScaleCode,severityScaleType);
		    	serviceStatus.setResult(maintSeverityScale);
			    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 getMaintSeverityScale(@RequestParam("legalEntityCode")String legalEntityCodeStr){
		ServiceStatus serviceStatus=new ServiceStatus();
		if(!BankAuditUtil.isEmptyString(legalEntityCodeStr)){
			try {
				logger.info("getMaintSeverityScale .."+ legalEntityCodeStr);
				Integer legalEntityCode=Integer.parseInt(legalEntityCodeStr);
				List<MaintSeverityScale> maintSeverityScales = maintSeverityScaleService.getMaintProbabilityScale(legalEntityCode);
				if(maintSeverityScales!=null && !maintSeverityScales.isEmpty()){
					serviceStatus.setStatus("success");
					serviceStatus.setMessage("successfuly retrieved");
					serviceStatus.setResult(maintSeverityScales);
				} 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;
	}
}
