/*
 * 
 */
package com.bankaudit.rest.controller;

import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.hibernate.boot.registry.classloading.spi.ClassLoaderService.Work;
import org.jboss.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;

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.RestController;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.http.MediaType;

import com.bankaudit.dto.DataTableResponse;
import com.bankaudit.model.MaintAuditParameter;
import com.bankaudit.model.MaintAuditParameterWrk;
import com.bankaudit.process.model.AuditProcessValidate;
import com.bankaudit.process.model.MaintAuditParameterWrapper;
import com.bankaudit.service.BusinessDateService;
import com.bankaudit.service.MaintAuditParameterService;
import com.bankaudit.util.BankAuditUtil;
import com.bankaudit.util.ServiceStatus;


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



@RestController

@RequestMapping("/api/maintAuditParameter")
public class MaintAuditParameterController {
	
	/**
	 * The maint audit parameter service is autowired and make methods available
	 * from service layer .
	 */
	@Autowired
	MaintAuditParameterService maintAuditParameterService;
	
	/**
	 * The business date service is autowired and make methods available from
	 * service layer .
	 */
	@Autowired
	BusinessDateService businessDateService;
	
	/** The Constant logger is used to specify the . */
	static final Logger logger = Logger.getLogger(MaintAuditParameterController.class);
	
	/**
	 * This method is use to Creates the maint audit parameter.
	 *
	 * @param maintAuditParameter
	 *            specify the maint audit parameter
	 * @return the service status class object with response status and payload
	 *         .
	 */
	
@RequestMapping(method=RequestMethod.POST,produces=MediaType.APPLICATION_JSON_VALUE,consumes=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus createMaintAuditParameter(@RequestBody MaintAuditParameter maintAuditParameter ) {
		
		ServiceStatus serviceStatus = new ServiceStatus();
		System.out.println("Inside createMaintAuditParameter ## .... ");
		try{
			if(maintAuditParameter!=null && maintAuditParameter.getLegalEntityCode()>0 && !BankAuditUtil.isEmptyString(maintAuditParameter.getAuditTypeCode()) ){  
				// maintAuditParameter.setStatus("A");
				maintAuditParameter.setBusinessdateTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(maintAuditParameter.getLegalEntityCode()));
				//maintAuditParameter.setBusinessdateTimestamp(new Timestamp(System.currentTimeMillis()));
				maintAuditParameter.setSysdateTimestamp(new Timestamp(System.currentTimeMillis()));
				maintAuditParameter.setMakerTimestamp(maintAuditParameter.getBusinessdateTimestamp());
				System.out.println("Bfr ....");
				maintAuditParameterService.createMaintAddress(maintAuditParameter);
				    serviceStatus.setStatus("success");
				    serviceStatus.setMessage("successfully created");
			}else {
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("invalid payload ");
			}
		}catch (Exception e) {
			e.printStackTrace();
			logger.info("Inside exception createMaintAuditParameter ......");
			serviceStatus.setStatus("failure");
			if(e instanceof org.springframework.dao.DataIntegrityViolationException) {
				serviceStatus.setMessage("DATAINTGRTY_VIOLATION");
			}else serviceStatus.setMessage("EXCP_OCCURED");
		}
		return serviceStatus;
	}
	
	/**
	 * This method is use to Update maint audit parameter.
	 *
	 * @param maintAuditParameter
	 *            specify the maint audit parameter
	 * @return the service status class object with response status and payload
	 *         .
	 */
	
@RequestMapping(method=RequestMethod.PUT,produces=MediaType.APPLICATION_JSON_VALUE,consumes=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus updateMaintAuditParameter(@RequestBody MaintAuditParameter maintAuditParameter) {
		
		ServiceStatus serviceStatus = new ServiceStatus();
		System.out.println("Inside updateMaintAuditParameter .... ");
		try{
			
			if(maintAuditParameter!=null && maintAuditParameter.getLegalEntityCode()>0 && !BankAuditUtil.isEmptyString(maintAuditParameter.getAuditTypeCode()) ){
				//maintAuditParameter.setStatus("A");
				maintAuditParameter.setBusinessdateTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(maintAuditParameter.getLegalEntityCode()));
				maintAuditParameter.setSysdateTimestamp(new Timestamp(System.currentTimeMillis()));
				maintAuditParameter.setMakerTimestamp(maintAuditParameter.getBusinessdateTimestamp());
				    maintAuditParameterService.updateMaintAuditParameter(maintAuditParameter);
				    
				    serviceStatus.setStatus("success");
				    serviceStatus.setMessage("successfully created");
			}else {
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("invalid payload ");
			}
		}catch (Exception e) {
			e.printStackTrace();
			serviceStatus.setStatus("failure");
			serviceStatus.setMessage("failure"+e.getMessage());
			if(e instanceof org.springframework.dao.DataIntegrityViolationException) {
				serviceStatus.setMessage("DATAINTGRTY_VIOLATION");
			}
		}
		return serviceStatus;
	}
	
	
	
@RequestMapping(value="/isMaintAuditParameterAlreadyExist",method=RequestMethod.POST,produces=MediaType.APPLICATION_JSON_VALUE,consumes=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus isMaintAuditParameterAlreadyExist(@RequestBody MaintAuditParameterWrk maintAuditParameter) {
		ServiceStatus serviceStatus = new ServiceStatus();
		System.out.println("Inside updateMaintAuditParameter .... " +maintAuditParameter);
		try{
			Boolean status = null;
			boolean isExist = false;
			Map dataExist = null;
			
			if(maintAuditParameter!=null && maintAuditParameter.getLegalEntityCode()>0 && !BankAuditUtil.isEmptyString(maintAuditParameter.getAuditTypeCode()) ){
				dataExist=maintAuditParameterService.isMaintAuditParameterAlreadyExist(maintAuditParameter); 
				/*if(!dataExist)	{		
					serviceStatus.setStatus("success");
					serviceStatus.setMessage("Record is not exists. Please continue to save new record.");
				}else {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("Record is already exists with same combinations.");	
				}*/
				
				if(dataExist!=null && dataExist.size()>0) {
					status=(Boolean)dataExist.get("isExist");
					isExist=status.booleanValue();
					if(isExist) {
						serviceStatus.setStatus("success");
						serviceStatus.setMessage("Record is not exists. Please continue to save new record.");
						serviceStatus.setResult(dataExist);
					}else {
						serviceStatus.setStatus("failure");
						serviceStatus.setMessage("Record is already exists with same combinations.");
						serviceStatus.setResult(dataExist);
					}
				}
				

			}else {
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("invalid payload ");
			}
		}catch (Exception e) {
			e.printStackTrace();
			serviceStatus.setStatus("failure");
			serviceStatus.setMessage("failure"+e.getMessage());
			if(e instanceof org.springframework.dao.DataIntegrityViolationException) {
				serviceStatus.setMessage("DATAINTGRTY_VIOLATION");
			}
		}
		return serviceStatus;
	}
	
	
	/**
	 * This method is use to Validate audit process.
	 *
	 * @param maintAuditParameterWrapper
	 *            specify the maint audit parameter wrapper
	 * @return the service status class object with response status and payload
	 *         .
	 */
	//MaintAuditParameterWrapper
	
@RequestMapping(value="/maintAuditParameterWrapper",method=RequestMethod.PUT,produces=MediaType.APPLICATION_JSON_VALUE,consumes=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus validateAuditProcess(@RequestBody MaintAuditParameterWrapper maintAuditParameterWrapper){
		ServiceStatus serviceStatus = new ServiceStatus();
		System.out.println("Inside authorizeMaintAuditParameters .... 1  ");
		try{
			if(maintAuditParameterWrapper!=null &&  maintAuditParameterWrapper.getMaintAuditParameterList()!=null) {
				List<MaintAuditParameter> maintAuditParameterLst= maintAuditParameterWrapper.getMaintAuditParameterList();
				if(maintAuditParameterLst!=null && maintAuditParameterLst.size()>0){
					Date businessDate=businessDateService.getBusinessDateTimestampByLegalEntityCode(maintAuditParameterLst.get(0).getLegalEntityCode());
					Timestamp currentTimeStamp=new Timestamp(System.currentTimeMillis());
					 maintAuditParameterService.updateMaintAuditsParameters(maintAuditParameterLst,businessDate,currentTimeStamp); 
					 serviceStatus.setStatus("success");
					 serviceStatus.setMessage("successfully created");
				}else {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("No data tobe save...");
				}
			}
			
		}catch (Exception e) {
			e.printStackTrace();
			serviceStatus.setStatus("failure");
			serviceStatus.setMessage("failure"+e.getMessage());
			if(e instanceof org.springframework.dao.DataIntegrityViolationException) {
				serviceStatus.setMessage("DATAINTGRTY_VIOLATION");
			}
		}
		return serviceStatus;
	}
	
	/**
	 * This method is use to Validate audit process.
	 *
	 * @param maintAuditParameterList
	 *            specify the maint audit parameter list
	 * @return the service status class object with response status and payload
	 *         
	 */
	//MaintAuditParameterWrapper
		
@RequestMapping(value="/maintAuditParameterList",method=RequestMethod.PUT,produces=MediaType.APPLICATION_JSON_VALUE,consumes=MediaType.APPLICATION_JSON_VALUE)
			ServiceStatus validateAuditProcess(@RequestBody List<MaintAuditParameter> maintAuditParameterList) {
			ServiceStatus serviceStatus = new ServiceStatus();
			System.out.println("Inside authorizeMaintAuditParameters .... 2 ");
			try{
					if(maintAuditParameterList!=null && maintAuditParameterList.size()>0){
						Date d=businessDateService.getBusinessDateTimestampByLegalEntityCode(maintAuditParameterList.get(0).getLegalEntityCode());
						Timestamp t=new Timestamp(System.currentTimeMillis());
						 maintAuditParameterService.updateMaintAuditsParameters(maintAuditParameterList,d,t); 
						 serviceStatus.setStatus("success");
						 serviceStatus.setMessage("successfully created");
						 
						 // Method call to derive the Audit parameter values for all possible combination
						 //MaintAuditParameterController m= new MaintAuditParameterController();
						//System.out.println("Bfr entering into updateMaintAuditsParametersDerived ....... ");
						
						if(("A").equalsIgnoreCase(maintAuditParameterList.get(0).getStatus())) {
							boolean exeParamMatrix=maintAuditParameterService.updateMaintAuditsParametersDerived(maintAuditParameterList.get(0).getLegalEntityCode(),maintAuditParameterList.get(0).getAuditTypeCode());
							logger.info("Maint Audit Parameter Derived table Updated .. ");
						}
						 // end here
					}else {
						serviceStatus.setStatus("failure");
						serviceStatus.setMessage("No data tobe save...");
					}
			}catch (Exception e) {
				e.printStackTrace();
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("failure"+e.getMessage());
				if(e instanceof org.springframework.dao.DataIntegrityViolationException) {
					serviceStatus.setMessage("DATAINTGRTY_VIOLATION");
				}
			}
			return serviceStatus;
		}
			
	/**
	 * This method is use to Gets the audit parameter.
	 *
	 * @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
	 * @param entitlement
	 *            specify the entitlement
	 * @param userName
	 *            specify the user name
	 * @param auditTypeCode
	 *            specify the audit type code
	 * @return the data table response class object with response status and
	 *         payload .
	 */
	
@RequestMapping(value="/getAll",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE) 
	DataTableResponse getAuditParameter(
			@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,
			@RequestParam(required=false, value="entitlement")String entitlement,
			@RequestParam("userName")String userName,
			@RequestParam(required=false, value="auditTypeCode")String auditTypeCode){
		
		
		DataTableResponse dataTableResponse=null;
		System.out.println("auditTypeCode .... "+auditTypeCode);
		if(!BankAuditUtil.isEmptyString(drawStr)
				&& !BankAuditUtil.isEmptyString(length)
				&& !BankAuditUtil.isEmptyString(start)
				&& !BankAuditUtil.isEmptyString(legalEntityCodeStr)			
				&& !BankAuditUtil.isEmptyString(userName)
				){
			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 =  maintAuditParameterService.getAuditParameter(legalEntityCode,auditTypeCode,entitlement,userName,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;
	}
	
	/*
@RequestMapping(value="/getAllbyAuditType",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE) 
	DataTableResponse getMaintAuditParametersByAudittype(
			@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,
			@RequestParam("auditTypeCode")String auditTypeCode){
		DataTableResponse dataTableResponse=null;
		if(!BankAuditUtil.isEmptyString(drawStr)
				&& !BankAuditUtil.isEmptyString(length)
				&& !BankAuditUtil.isEmptyString(start)
				&& !BankAuditUtil.isEmptyString(legalEntityCodeStr)
				&& !BankAuditUtil.isEmptyString(auditTypeCode)){
			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 = maintAuditParameterService.getAuditParameter(legalEntityCode,auditTypeCode,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 maint audit parameters by audittype.
	 *
	 * @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 = "/get/{legalEntityCode}/{auditTypeCode}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus getMaintAuditParametersByAudittype(@PathVariable("legalEntityCode") Integer legalEntityCode,
			@PathVariable("auditTypeCode") String auditTypeCode
			) {
		ServiceStatus serviceStatus = new ServiceStatus();
		if (legalEntityCode != null
				&& !BankAuditUtil.isEmptyString(auditTypeCode) 
				) {
			try {
				List<MaintAuditParameter> maintAuditParameter = maintAuditParameterService.getMaintAuditParameterbyAuditType(legalEntityCode,auditTypeCode);
				if (maintAuditParameter != null) {
					serviceStatus.setResult(maintAuditParameter);
					serviceStatus.setStatus("success");
					serviceStatus.setMessage("successfully retrieved ");
				} else {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("MaintAuditSubgroup not found");
				}
			} catch (Exception e) {
				e.printStackTrace();
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("failure");
			}
		} else {
			serviceStatus.setStatus("failure");
			serviceStatus.setMessage("invalid payload ");
		}
		return serviceStatus;
	}
	
	
	
	
@RequestMapping(value = "/getMaintAuditParametersPreviousRatingLov/{legalEntityCode}/{auditTypeCode}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus getMaintAuditParametersPreviousRatingLov(@PathVariable("legalEntityCode") Integer legalEntityCode,
			@PathVariable("auditTypeCode") String auditTypeCode
			) {
		ServiceStatus serviceStatus = new ServiceStatus();
		if (legalEntityCode != null
				&& !BankAuditUtil.isEmptyString(auditTypeCode) 
				) {
			try {
				List<Object[]> maintAuditParameter = maintAuditParameterService.getMaintAuditParametersPreviousRatingLov(legalEntityCode,auditTypeCode);
				if (maintAuditParameter != null) {
					serviceStatus.setResult(maintAuditParameter);
					serviceStatus.setStatus("success");
					serviceStatus.setMessage("successfully retrieved ");
				} else {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("MaintAuditSubgroup not found");
				}
			} catch (Exception e) {
				e.printStackTrace();
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("failure");
			}
		} else {
			serviceStatus.setStatus("failure");
			serviceStatus.setMessage("invalid payload ");
		}
		return serviceStatus;
	}
	
	
	
	
@RequestMapping(value = "/setAuditParamAll/{legalEntityCode}/{auditTypeCode}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus updateMaintAuditsParametersDerived(@PathVariable("legalEntityCode") Integer legalEntityCode,
			@PathVariable("auditTypeCode") String auditTypeCode
			){
		
		ServiceStatus serviceStatus = new ServiceStatus();
		System.out.println("Inside updateMaintAuditParameterDerived .... ");
		try{
			
			if(legalEntityCode!=null && auditTypeCode != null) {
				    maintAuditParameterService.updateMaintAuditsParametersDerived(legalEntityCode, auditTypeCode);
				    
				    serviceStatus.setStatus("success");
				    serviceStatus.setMessage("successfully created");
			}else {
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("invalid payload ");
			}
		}catch (Exception e) {
			e.printStackTrace();
			serviceStatus.setStatus("failure");
			serviceStatus.setMessage("failure"+e.getMessage());
			if(e instanceof org.springframework.dao.DataIntegrityViolationException) {
				serviceStatus.setMessage("DATAINTGRTY_VIOLATION");
			}
		}
		return serviceStatus;
	}
	
	
	
@RequestMapping(value="/getAllAuditParamDerived",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE) 
	DataTableResponse getAuditParameterDerived(
			@RequestParam("draw") String drawStr,
			@RequestParam(required= false, value="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,
			@RequestParam(required=false, value="entitlement")String entitlement,
			@RequestParam("userName")String userName,
			@RequestParam(required=false, value="auditTypeCode")String auditTypeCode){
		
		
		DataTableResponse dataTableResponse=null;
		logger.info("Inside getAllAuditParamDerived auditTypeCode .... "+auditTypeCode +" legalEntityCode .... "+legalEntityCodeStr);
		if(!BankAuditUtil.isEmptyString(drawStr)
				&& !BankAuditUtil.isEmptyString(length)
				&& !BankAuditUtil.isEmptyString(start)
				&& !BankAuditUtil.isEmptyString(legalEntityCodeStr)			
				&& !BankAuditUtil.isEmptyString(userName)
				){
			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 =  maintAuditParameterService.getAuditParameterDerived(legalEntityCode,auditTypeCode,entitlement,userName,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;
	}
	
	
	
@RequestMapping(value="/deleteMaintAuditParameter/{legalEntityCode}/{auditTypeCode}/{id}/{status}",method=RequestMethod.DELETE,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus deleteEntityLevelCodeDescByLegalEntityCodeAndLevelCode(
			@PathVariable("legalEntityCode")Integer legalEntityCode,
			@PathVariable("auditTypeCode")String auditTypeCode,
			@PathVariable("id")Integer id,
			@PathVariable("status")String status){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(legalEntityCode!=null
				&& !BankAuditUtil.isEmptyString(auditTypeCode)){
			try {				
				maintAuditParameterService.deleteMaintAuditParameter(legalEntityCode, auditTypeCode, id, status);
				serviceStatus.setStatus("success"); 
			    serviceStatus.setMessage("successfully deleted the selected record ");					
			} catch (Exception e) {
				e.printStackTrace();
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("failure");
			}
		}else {
			serviceStatus.setStatus("failure");
			serviceStatus.setMessage("invalid legalEntityCode ");
		}
		
		return serviceStatus;
	}	
	
}
