/*
 * 
 */
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.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.constants.BankAuditConstant;
import com.bankaudit.dto.DataTableResponse;
import com.bankaudit.model.RiskScoreAuditGrp;
import com.bankaudit.service.BusinessDateService;
import com.bankaudit.service.RiskScoreAuditGrpService;
import com.bankaudit.util.BankAuditUtil;
import com.bankaudit.util.ServiceStatus;



/**
 * The Class {@link RiskScoreAuditGrpController} provides the REST services to
 * manage the {@link RiskScoreAuditGrp} class objects .
 *
 * @author amit.patel
 * @version 1.0
 */

@RestController

@RequestMapping("/api/riskScoreAuditGrp")
public class RiskScoreAuditGrpController {

	/**
	 * The risk score audit grp service is autowired and make methods available
	 * from service layer .
	 */
	@Autowired
	RiskScoreAuditGrpService riskScoreAuditGrpService;
	
	/**
	 * The business date service is autowired and make methods available from
	 * service layer .
	 */
	@Autowired
	BusinessDateService businessDateService;
	
	/** The Constant logger is used to specify the . */
	@Autowired
	
	static final Logger logger = Logger.getLogger(RiskScoreAuditGrpController.class);
	
	/**
	 * This method is use to Creates the risk score audit grp.
	 *
	 * @param riskScoreAuditGrps
	 *            specify the risk score audit grps
	 * @return the service status class object with response status and payload
	 *         .
	 */
	
@RequestMapping(method=RequestMethod.POST,consumes=MediaType.APPLICATION_JSON_VALUE,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus createRiskScoreAuditGrp(@RequestBody List<RiskScoreAuditGrp> riskScoreAuditGrps){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(riskScoreAuditGrps!=null && !riskScoreAuditGrps.isEmpty()){
			try {
				
				Boolean flag=false;
				Integer totalWeightage=0;
				for (RiskScoreAuditGrp riskScoreAuditGrp : riskScoreAuditGrps) {

					if(riskScoreAuditGrp!=null
							&& riskScoreAuditGrp.getLegalEntityCode()!=null
							&& !BankAuditUtil.isEmptyString(riskScoreAuditGrp.getAuditGroupCode())
							&& !BankAuditUtil.isEmptyString(riskScoreAuditGrp.getAuditTypeCode())
							&& riskScoreAuditGrp.getWeightage()!=null
							&& riskScoreAuditGrp.getWeightage() <=100
							&& !BankAuditUtil.isEmptyString(riskScoreAuditGrp.getMaker())
							){ 
						riskScoreAuditGrp.setBusinessdateTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(riskScoreAuditGrp.getLegalEntityCode()));
						riskScoreAuditGrp.setSysdateTimestamp(new Timestamp(System.currentTimeMillis()));
						riskScoreAuditGrp.setMakerTimestamp(riskScoreAuditGrp.getBusinessdateTimestamp());
						flag=true;
						totalWeightage=totalWeightage+riskScoreAuditGrp.getWeightage();
					}else {
						flag=false;
						break;
					}
				}
				
				if(flag){
					if(totalWeightage==100){
						
						riskScoreAuditGrpService.createRiskScoreAuditGrp(riskScoreAuditGrps);
						serviceStatus.setStatus("success");
						serviceStatus.setMessage("successfully created");
						
					}else {
						serviceStatus.setStatus("failure");
						serviceStatus.setMessage("totalWeightage is not 100");
					}
				}else {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("invalid payload");
				}
			
			} 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("empty riskScoreAuditGrps");
		}
		
		return serviceStatus;
	}
	
	/**
	 * This method is use to Update risk score audit grp.
	 *
	 * @param riskScoreAuditGrps
	 *            specify the risk score audit grps
	 * @return the service status class object with response status and payload
	 *         .
	 */
	
@RequestMapping(method=RequestMethod.PUT,consumes=MediaType.APPLICATION_JSON_VALUE,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus updateRiskScoreAuditGrp(@RequestBody List<RiskScoreAuditGrp> riskScoreAuditGrps){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(riskScoreAuditGrps!=null && !riskScoreAuditGrps.isEmpty()){
			try {
				
				Boolean flag=false;
				Integer totalWeightage=0;
				for (RiskScoreAuditGrp riskScoreAuditGrp : riskScoreAuditGrps) {

					if(riskScoreAuditGrp!=null
							&& riskScoreAuditGrp.getLegalEntityCode()!=null
							&& !BankAuditUtil.isEmptyString(riskScoreAuditGrp.getAuditGroupCode())
							&& !BankAuditUtil.isEmptyString(riskScoreAuditGrp.getAuditTypeCode())
							&& riskScoreAuditGrp.getWeightage()!=null
							&& riskScoreAuditGrp.getWeightage() <=100
							&& !BankAuditUtil.isEmptyString(riskScoreAuditGrp.getMaker())
							){ 
						riskScoreAuditGrp.setBusinessdateTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(riskScoreAuditGrp.getLegalEntityCode()));
						riskScoreAuditGrp.setSysdateTimestamp(new Timestamp(System.currentTimeMillis()));
						
						if(riskScoreAuditGrp.getStatus().equals(BankAuditConstant.STATUS_AUTH)){
							riskScoreAuditGrp.setCheckerTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(riskScoreAuditGrp.getLegalEntityCode()));
						}else{
							riskScoreAuditGrp.setMakerTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(riskScoreAuditGrp.getLegalEntityCode()));
						}
						
						flag=true;
						totalWeightage=totalWeightage+riskScoreAuditGrp.getWeightage();
					}else {
						flag=false;
						break;
					}
				}
				
				if(flag){
					if(totalWeightage==100){
						
						riskScoreAuditGrpService.updateRiskScoreAuditGrp(riskScoreAuditGrps);
						serviceStatus.setStatus("success");
						serviceStatus.setMessage("successfully updated");
						
					}else {
						serviceStatus.setStatus("failure");
						serviceStatus.setMessage("totalWeightage is not 100");
					}
				}else {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("invalid payload");
				}
			
			} 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("empty riskScoreAuditGrps");
		}
		
		return serviceStatus;
	}
	
	/**
	 * This method is use to Gets the risk score audit grp.
	 *
	 * @param legalEntityCode
	 *            specify the legal entity code
	 * @param auditGroupCode
	 *            specify the audit group code
	 * @param auditTypeCode
	 *            specify the audit type code
	 * @return the service status class object with response status and payload
	 *         .
	 */
	
@RequestMapping(value="/getByLegalEntityCodeAndAuditTypeCodeOrAuditGroupCode",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus getRiskScoreAuditGrp(@RequestParam("legalEntityCode")String legalEntityCode,
			@RequestParam(required=false,value="auditGroupCode") String auditGroupCode,
			@RequestParam("auditTypeCode") String auditTypeCode
			){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(!BankAuditUtil.isEmptyString(legalEntityCode)
				&& !BankAuditUtil.isEmptyString(auditTypeCode)){
			
			try {
				
			    List<RiskScoreAuditGrp> RiskScoreAuditGrp=riskScoreAuditGrpService.getRiskScoreAuditGrp(Integer.parseInt(legalEntityCode),auditGroupCode,auditTypeCode);
			    if(RiskScoreAuditGrp!=null && !RiskScoreAuditGrp.isEmpty()){
			    	serviceStatus.setResult(RiskScoreAuditGrp);
				    serviceStatus.setStatus("success");
				    serviceStatus.setMessage("successfully retrieved ");	
			    }else {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("RiskScoreAuditGrp not found");
				}
				
			} catch (Exception e) {
				e.printStackTrace();
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("failure");
			}
			
		}else {
			serviceStatus.setStatus("failure");
			serviceStatus.setMessage("invalid payload ");
		}
		
		return serviceStatus;
	}
	

	/**
	 * This method is use to Gets the risk score audit grps.
	 *
	 * @param drawStr
	 *            specify the draw str
	 * @param length
	 *            specify the length
	 * @param start
	 *            specify the start
	 * @param search
	 *            specify the search
	 * @param orderColumnStr
	 *            specify the order column str
	 * @param orderDirection
	 *            specify the order direction
	 * @param legalEntityCodeStr
	 *            specify the legal entity code str
	 * @return the data table response class object with response status and
	 *         payload .
	 */
	
@RequestMapping(value="/getAll",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE) 
	DataTableResponse getRiskScoreAuditGrps(
			@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 legalEntityCode=Integer.parseInt(legalEntityCodeStr);
				Integer draw=Integer.parseInt(drawStr);
				Integer size=Integer.parseInt(length);
				Integer page=Integer.parseInt(start)/size;
				Integer orderColumn=null;
				if(!BankAuditUtil.isEmptyString(orderColumnStr)){
					orderColumn=Integer.parseInt(orderColumnStr);
				}
				dataTableResponse = riskScoreAuditGrpService.getRiskScoreAuditGrps(legalEntityCode,search,orderColumn,orderDirection,page,size);
				dataTableResponse.setDraw(draw);    
					
			} catch (Exception e) {
                dataTableResponse=new DataTableResponse();
                dataTableResponse.setError(e.getMessage());
				e.printStackTrace();
			}
		
		}else {
			dataTableResponse=new DataTableResponse();
			dataTableResponse.setError("invalid data");
		}
		
		return dataTableResponse;
	}

	
	/**
	 * This method is use to Gets the risk score audit grp by legal entity code
	 * and audit type code.
	 *
	 * @param legalEntityCode
	 *            specify the legal entity code
	 * @param auditTypeCode
	 *            specify the audit type code
	 * @param status
	 *            specify the status
	 * @return the service status class object with response status and payload
	 *         .
	 */
	
@RequestMapping(value="/getByLegalEntityCodeAndAuditTypeCode",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus getRiskScoreAuditGrpByLegalEntityCodeAndAuditTypeCode(@RequestParam("legalEntityCode")String legalEntityCode,
			@RequestParam("auditTypeCode") String auditTypeCode,
			@RequestParam("status") String status
			){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(!BankAuditUtil.isEmptyString(legalEntityCode)
				&& !BankAuditUtil.isEmptyString(auditTypeCode)){
			
			try {
				
			    List<RiskScoreAuditGrp> RiskScoreAuditGrp=riskScoreAuditGrpService.getRiskScoreAuditGrpByLegalEntityCodeAndAuditTypeCode(Integer.parseInt(legalEntityCode),auditTypeCode,status);
			    if(RiskScoreAuditGrp!=null && !RiskScoreAuditGrp.isEmpty()){
			    	serviceStatus.setResult(RiskScoreAuditGrp);
				    serviceStatus.setStatus("success");
				    serviceStatus.setMessage("successfully retrieved ");	
			    }else {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("RiskScoreAuditGrp not found");
				}
				
			} catch (Exception e) {
				e.printStackTrace();
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("failure");
			}
			
		}else {
			serviceStatus.setStatus("failure");
			serviceStatus.setMessage("invalid payload ");
		}
		
		return serviceStatus;
	}
	
	
	/**
	 * This method is use to Checks if is risk score audit grp.
	 *
	 * @param legalEntityCode
	 *            specify the legal entity code
	 * @param auditTypeCode
	 *            specify the audit type code
	 * @return the service status class object with response status and payload
	 *         .
	 */
	
@RequestMapping(value="/isRiskScoreAuditGrp",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus isRiskScoreAuditGrp(@RequestParam("legalEntityCode")String legalEntityCode,
			@RequestParam("auditTypeCode") String auditTypeCode
			){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(!BankAuditUtil.isEmptyString(legalEntityCode)
				&& !BankAuditUtil.isEmptyString(auditTypeCode)){
			
			try {
				
			    Boolean flag =riskScoreAuditGrpService.isRiskScoreAuditGrp(Integer.parseInt(legalEntityCode),auditTypeCode);
			
				    serviceStatus.setStatus("success");
				    serviceStatus.setMessage("successfully got result ");	
				    serviceStatus.setResult(flag);
				
			} catch (Exception e) {
				e.printStackTrace();
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("failure");
			}
			
		}else {
			serviceStatus.setStatus("failure");
			serviceStatus.setMessage("invalid payload");
		}
		
		return serviceStatus;
	}
	
}
