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

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

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.constants.BankAuditConstant;
import com.bankaudit.dto.DataTableResponse;
import com.bankaudit.model.MaintEntity;
import com.bankaudit.model.MaintEntityWrk;
import com.bankaudit.model.User;
import com.bankaudit.service.BusinessDateService;
import com.bankaudit.service.MaintEntityService;
import com.bankaudit.service.UserService;
import com.bankaudit.util.BankAuditUtil;
import com.bankaudit.util.ServiceStatus;


/**
 * {@link MaintEntityController} class provides the rest end points to Create,
 * Read, Update and delete the {@link MaintEntity} class objects.
 *
 * @author amit.patel
 */


@RestController

@RequestMapping("/api/maintEntity")
public class MaintEntityController {

	/**
	 * The maint entity service is autowired and make methods available from
	 * service layer .
	 */
	@Autowired 
	MaintEntityService maintEntityService;
	
	/**
	 * The business date service is autowired and make methods available from
	 * service layer .
	 */
	@Autowired
	BusinessDateService businessDateService;
	
	@Autowired
	UserService userService;
	
	static final Logger logger = Logger.getLogger(MaintEntityController.class);
	
	/**
	 * This method is use to Creates the maint entity.
	 *
	 * @param maintEntityWrk
	 *            specify the maint entity wrk
	 * @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 createMaintEntity(@RequestBody MaintEntityWrk maintEntityWrk){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(maintEntityWrk!=null
				/*&& maintEntityWrk!=null*/
				&& maintEntityWrk.getUnitCode()!=null
				&& maintEntityWrk.getLegalEntityCode()!=null
				&& !BankAuditUtil.isEmptyString(maintEntityWrk.getMaker())
				&& BankAuditUtil.isNumber(maintEntityWrk.getMobile1()) && BankAuditUtil.isNumber(maintEntityWrk.getMobile2()) && BankAuditUtil.isNumber(maintEntityWrk.getLandline1())
				){
			try {
				maintEntityWrk.setBusinessdateTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(maintEntityWrk.getLegalEntityCode()));
				maintEntityWrk.setSysdateTimestamp(new Timestamp(System.currentTimeMillis()));
				maintEntityWrk.setMakerTimestamp(maintEntityWrk.getBusinessdateTimestamp());
				maintEntityService.createMaintEntity(maintEntityWrk);
				serviceStatus.setStatus("success");
				serviceStatus.setMessage("successfully saved");
			} catch (Exception e) {
				serviceStatus.setStatus("failure");
				
				e.printStackTrace();
				if(e instanceof org.springframework.dao.DataIntegrityViolationException) {
					serviceStatus.setMessage("DATAINTGRTY_VIOLATION");
				}
				serviceStatus.setMessage("failure");
			}

		}else {
			serviceStatus.setStatus("failure");
			serviceStatus.setMessage("invalid payload");
		}
				
		
		return serviceStatus;
	}
	
	/**
	 * This method is use to Update maint entity.
	 *
	 * @param maintEntityWrk
	 *            specify the maint entity wrk
	 * @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 updateMaintEntity(@RequestBody MaintEntityWrk maintEntityWrk){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(maintEntityWrk!=null
				&& maintEntityWrk.getUnitCode()!=null
				&& maintEntityWrk.getLegalEntityCode()!=null
				&& BankAuditUtil.isNumber(maintEntityWrk.getMobile1()) && BankAuditUtil.isNumber(maintEntityWrk.getMobile2()) && BankAuditUtil.isNumber(maintEntityWrk.getLandline1())
				){
			try {
				maintEntityWrk.setBusinessdateTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(maintEntityWrk.getLegalEntityCode()));
				maintEntityWrk.setSysdateTimestamp(new Timestamp(System.currentTimeMillis()));
				if(maintEntityWrk.getStatus().equals(BankAuditConstant.STATUS_AUTH)){
					maintEntityWrk.setCheckerTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(maintEntityWrk.getLegalEntityCode()));
				}else{
					maintEntityWrk.setMakerTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(maintEntityWrk.getLegalEntityCode()));
				}
				maintEntityService.updateMaintEntity(maintEntityWrk);
				serviceStatus.setStatus("success");
				serviceStatus.setMessage("successfully updated");
				
			} catch (Exception e) {
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("failure");
				e.printStackTrace();
				if(e instanceof org.springframework.dao.DataIntegrityViolationException) {
					serviceStatus.setMessage("DATAINTGRTY_VIOLATION");
				}
			}

		}else {
			serviceStatus.setStatus("failure");
			serviceStatus.setMessage("invalid payload");
		}
				
		
		return serviceStatus;
	}
	
	
	/**
	 * This method is use to Gets the maint entity by legal entity code and unit
	 * code.
	 *
	 * @param legalEntityCode
	 *            specify the legal entity code
	 * @param unitCode
	 *            specify the unit code
	 * @param status
	 *            specify the status
	 * @return the service status class object with response status and payload
	 *         .
	 */
	
@RequestMapping(value="/getByLegalEntityCodeAndUnitCode/{legalEntityCode}/{unitCode}/{status}",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus getMaintEntityByLegalEntityCodeAndUnitCode(
			@PathVariable("legalEntityCode") Integer legalEntityCode,
			@PathVariable("unitCode")String unitCode,
			@PathVariable("status")String status){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(legalEntityCode!=null
				&& !BankAuditUtil.isEmptyString(unitCode)
				&& !BankAuditUtil.isEmptyString(status)){
			try {
				MaintEntity maintEntity=maintEntityService.getUnique(legalEntityCode,unitCode,status);
				
				if(maintEntity!=null){
					serviceStatus.setResult(maintEntity);
					serviceStatus.setStatus("success");
					serviceStatus.setMessage("successfuly retrieved ");
				}else {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("ids not found");
				}
				
			} catch (Exception e) {
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("failure");
				e.printStackTrace();
			}
			
		}else {
			serviceStatus.setStatus("failure");
			serviceStatus.setMessage("invalid parameter");
		}
				return serviceStatus;
	}
	
	
	
	/**
	 * This method is use to Gets the maint entity by legal entity code and
	 * level code.
	 *
	 * @param legalEntityCode
	 *            specify the legal entity code
	 * @param levelCode
	 *            specify the level code
	 * @return the service status class object with response status and payload
	 *         .
	 */
	
@RequestMapping(value="/getByLegalEntityCodeAndLevelCode/{legalEntityCode}/{levelCode}",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus getMaintEntityByLegalEntityCodeAndLevelCode(
			@PathVariable("legalEntityCode") Integer legalEntityCode,
			@PathVariable("levelCode")String levelCode){
		ServiceStatus serviceStatus=new ServiceStatus();
		//active inactive
		if(legalEntityCode!=null && !BankAuditUtil.isEmptyString(levelCode)){
			try {
				if("0".equalsIgnoreCase(levelCode))  // For Head office, whose parent unit is the same
					levelCode="1"; //
				List<MaintEntity> maintEntities=maintEntityService.getMaintEntityByLegalEntityCodeAndLevelCode(legalEntityCode,levelCode);
				
				if(maintEntities!=null&&!maintEntities.isEmpty()){
					serviceStatus.setResult(maintEntities);
					serviceStatus.setStatus("success");
					serviceStatus.setMessage("successfuly retrieved ");
				}else {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage(" not found any");
				}
				
			} catch (Exception e) {
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("failure");
				e.printStackTrace();
			}
			
		}else {
			serviceStatus.setStatus("failure");
			serviceStatus.setMessage("invalid parameter");
		}
				return serviceStatus;
	}
	
	
	/**
	 * This method is use to Gets Sub Branches by legalEntityCode and userId/UnitCode.
	 *
	 * @param legalEntityCode
	 *            specify the legal entity code
	 * @param levelCode
	 *            specify the level code
	 * @return the service status class object with response status and payload
	 *         .
	 */
	
@RequestMapping(value="/getSubBranchesGyUserIdOrUnitId/{legalEntityCode}/{type}/{userIdOrUnitId}",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus getSubBranchesGyUserIdOrUnitId(
			@PathVariable("legalEntityCode") Integer legalEntityCode,
			@PathVariable("role")String role,
			@PathVariable("type")String type,
			@PathVariable("userIdOrUnitId")String userIdOrUnitId){
		ServiceStatus serviceStatus=new ServiceStatus();
		//active inactive
		if(legalEntityCode!=null
				&& !BankAuditUtil.isEmptyString(userIdOrUnitId)){
			try {
				List<MaintEntity> maintEntities=maintEntityService.getSubBranchesGyUserIdOrUnitId(legalEntityCode,role,type,userIdOrUnitId);
				
				if(maintEntities!=null&&!maintEntities.isEmpty()){
					serviceStatus.setResult(maintEntities);
					serviceStatus.setStatus("success");
					serviceStatus.setMessage("successfuly retrieved ");
				}else {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage(" not found any");
				}
				
			} catch (Exception e) {
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("failure");
				e.printStackTrace();
			}
			
		}else {
			serviceStatus.setStatus("failure");
			serviceStatus.setMessage("invalid parameter");
		}
				return serviceStatus;
	}
	
	
	/**
	 * This method is use to Gets the maint entity.
	 *
	 * @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 levelCodeStr
	 *            specify the level code str
	 * @param parentUnitCode
	 *            specify the parent unit code
	 * @param userId
	 *            specify the user id
	 * @return the data table response class object with response status and
	 *         payload .
	 */
	
@RequestMapping(value="/getAll",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE) 
	DataTableResponse getMaintEntity(
			@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("levelCode") String levelCodeStr,
			@RequestParam("parentUnitCode") String parentUnitCode,
			@RequestParam("userId") String userId
			){
		
		DataTableResponse dataTableResponse=null;
		
		if(!BankAuditUtil.isEmptyString(drawStr)
				&& !BankAuditUtil.isEmptyString(length)
				&& !BankAuditUtil.isEmptyString(start)
				&& !BankAuditUtil.isEmptyString(legalEntityCodeStr)
				&& (!BankAuditUtil.isEmptyString(levelCodeStr) || !BankAuditUtil.isEmptyString(parentUnitCode))){
			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 = maintEntityService.getMaintEntity(legalEntityCode,levelCodeStr,userId,parentUnitCode,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 entity by legal entity code.
	 *
	 * @param legalEntityCode
	 *            specify the legal entity code
	 * @return the service status class object with response status and payload
	 *         .
	 */
	
@RequestMapping(value="/getByLegalEntityCode/{legalEntityCode}",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus getMaintEntityByLegalEntityCode(
			@PathVariable("legalEntityCode") Integer legalEntityCode
			){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(legalEntityCode!=null
				){
			try {
				List<MaintEntity> maintEntities=maintEntityService.getMaintEntityByLegalEntityCode(legalEntityCode);
				
				if(maintEntities!=null&&!maintEntities.isEmpty()){
					serviceStatus.setResult(maintEntities);
					serviceStatus.setStatus("success");
					serviceStatus.setMessage("successfuly retrieved ");
				}else {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage(" not found any");
				}
				
			} catch (Exception e) {
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("failure");
				e.printStackTrace();
			}
			
		}else {
			serviceStatus.setStatus("failure");
			serviceStatus.setMessage("invalid parameter");
		}
				return serviceStatus;
	}
	
	
@RequestMapping(value="/getByLegalEntityCode/{legalEntityCode}/{auditTypeCode}",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus getMaintEntityByLegalEntityCodeAndAuditTypeCode(
			@PathVariable("legalEntityCode") Integer legalEntityCode,@PathVariable("auditTypeCode") String auditTypeCode
			){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(legalEntityCode!=null
				){
			try {
				List<MaintEntity> maintEntities=maintEntityService.getMaintEntityByLegalEntityCodeAndAuditTypeCode(legalEntityCode, auditTypeCode);
				
				if(maintEntities!=null&&!maintEntities.isEmpty()){
					serviceStatus.setResult(maintEntities);
					serviceStatus.setStatus("success");
					serviceStatus.setMessage("successfuly retrieved ");
				}else {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage(" not found any");
				}
				
			} catch (Exception e) {
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("failure");
				e.printStackTrace();
			}
			
		}else {
			serviceStatus.setStatus("failure");
			serviceStatus.setMessage("invalid parameter");
		}
				return serviceStatus;
	}
	/**
	 * This method is use to Checks if is head user.
	 *
	 * @param legalEntityCodeStr
	 *            specify the legal entity code str
	 * @param userId
	 *            specify the user id
	 * @param unitCode
	 *            specify the unit code
	 * @return the service status class object with response status and payload
	 *         .
	 */
	
@RequestMapping(value="/isHeadUser",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus isHeadUser(
			@RequestParam(required=true,value="legalEntityCode") String legalEntityCodeStr,
			@RequestParam(required=true,value="userId") String userId,
			@RequestParam(required=false,value="unitCode") String unitCode
			){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(!BankAuditUtil.isEmptyString(legalEntityCodeStr)
				&& !BankAuditUtil.isEmptyString(userId)
				){
			Integer legalEntityCode=Integer.parseInt(legalEntityCodeStr);
			
			try {
				Boolean isHeadUser =maintEntityService.isHeadUser(legalEntityCode,userId,unitCode);
				serviceStatus.setResult(isHeadUser);
				serviceStatus.setStatus("success");
				serviceStatus.setMessage("successfuly retrieved ");
				
			} catch (Exception e) {
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("failure");
				e.printStackTrace();
			}
			
		}else {
			serviceStatus.setStatus("failure");
			serviceStatus.setMessage("invalid parameter");
		}
				return serviceStatus;
	}
	
	/**
	 * This method is use to Checks if is maint entity.
	 *
	 * @param legalEntityCode
	 *            specify the legal entity code
	 * @param unitCode
	 *            specify the unit code
	 * @return the service status class object with response status and payload
	 *         .
	 */
	
@RequestMapping(value="/isMaintEntity/{legalEntityCode}/{unitCode}",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus isMaintEntity(@PathVariable("legalEntityCode")Integer legalEntityCode,

			@PathVariable("unitCode") String unitCode
			){
		ServiceStatus serviceStatus=new ServiceStatus();
		if(legalEntityCode!=null 
				&&  !BankAuditUtil.isEmptyString(unitCode)){
			
			try {
			    Boolean maintEntity=maintEntityService.isMaintEntity(legalEntityCode,unitCode);
		    	serviceStatus.setResult(maintEntity);
			    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="/isChildActivated/{legalEntityCode}/{unitCode}",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus isChildActivated(@PathVariable("legalEntityCode")Integer legalEntityCode,
			@PathVariable("unitCode") String unitCode
			){
		ServiceStatus serviceStatus=new ServiceStatus();
		if(legalEntityCode!=null 
				&&  !BankAuditUtil.isEmptyString(unitCode)){
			
			try {
			    Boolean maintEntity=maintEntityService.isChildUnitActivated(legalEntityCode,unitCode);
		    	serviceStatus.setResult(maintEntity);
			    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="/isActiveChildAndUser/{legalEntityCode}/{unitCode}",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus isActiveChildAndUser(@PathVariable("legalEntityCode")Integer legalEntityCode,
			@PathVariable("unitCode") String unitCode){
		ServiceStatus serviceStatus=new ServiceStatus();
		logger.info("Inside isActiveChildAndUser .. "+ legalEntityCode + " :: "+ unitCode );
		if(legalEntityCode!=null &&  !BankAuditUtil.isEmptyString(unitCode)){
			
			try {
			    Boolean maintEntity=maintEntityService.isChildUnitActivated(legalEntityCode,unitCode);
			    List<User> users = userService.getAllActiveUsers(legalEntityCode,unitCode,BankAuditConstant.STATUS_ACTIVE);
			    Map<String, Boolean> map = new HashMap<String, Boolean>();
			    map.put("CHILD_ENTITY", maintEntity);
			    map.put("USERS", ( (users != null && users.size()> 0)? true: false ));
			    logger.info("map is .. "+ map);
			    serviceStatus.setResult(map);
			    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="/getMaintEntityByLEAndUser/{legalEntityCode}/{userId}/{role}/{unitCode}",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus getMaintEntityByLEAndUser(@PathVariable("legalEntityCode")Integer legalEntityCode,
			@PathVariable("userId")String userId,@PathVariable("role")String role,@PathVariable("unitCode")String unitCode
			){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(legalEntityCode!=null && !BankAuditUtil.isEmptyString(userId) && !BankAuditUtil.isEmptyString(role)
				){
			
			try {
				List<MaintEntity> maintEntities=maintEntityService.getMaintEntityByLEAndUser(legalEntityCode,userId,role,unitCode);
			    if(maintEntities!=null&& !maintEntities.isEmpty()){
			    	serviceStatus.setResult(maintEntities);
				    serviceStatus.setStatus("success");
				    serviceStatus.setMessage("successfully retrieved ");	
			    }else {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("MaintEntity 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 = "/getRiskManagerDetails", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus getRiskManagerDetails(
			@RequestParam(required=true,value="legalEntityCode") String legalEntityCode,
			@RequestParam(required=true,value="userId")String userId,
			@RequestParam(required=false,value="role")String role,
			@RequestParam(required=true,value="unit")String unitCode
			){
		ServiceStatus serviceStatus =new ServiceStatus();
		if(!BankAuditUtil.isEmptyString(legalEntityCode) &&!BankAuditUtil.isEmptyString(userId) &&!BankAuditUtil.isEmptyString(role)){
			try {
				Map<String, String> result  =	maintEntityService.getRiskManagerDetails(Integer.parseInt(legalEntityCode),
						userId, role, unitCode );
				serviceStatus.setResult(result);
			    serviceStatus.setStatus("success");
			    serviceStatus.setMessage("sucessfully retrieved");
			} catch (Exception e) {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("failure");
					e.printStackTrace();
			}
		}else {
			serviceStatus.setStatus("failure");
			serviceStatus.setMessage("legalEntityCode and period is required");
		}
		return serviceStatus;
	}
	
	// Service to delete the Records, 
	
@RequestMapping(value="/deleteMaintEntityByID/{legalEntityCode}/{unitCode}/{userId}",method=RequestMethod.DELETE,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus deleteMaintEntityByID(@PathVariable("legalEntityCode")Integer legalEntityCode,
			@PathVariable("unitCode") String unitCode,@PathVariable("userId") String userId){
	ServiceStatus serviceStatus=new ServiceStatus();
		if(legalEntityCode !=null && !BankAuditUtil.isEmptyString(unitCode) && !BankAuditUtil.isEmptyString(userId)){
			try {
				maintEntityService.deleteMaintEntityByID(legalEntityCode, unitCode, userId);
				serviceStatus.setStatus("success");
				serviceStatus.setMessage("Record deleted successfully.");
			} catch (Exception e) {
				serviceStatus.setStatus("failure");
				e.printStackTrace();
				if(e instanceof org.springframework.dao.DataIntegrityViolationException) {
					serviceStatus.setMessage("DATAINTGRTY_VIOLATION");
				}
				serviceStatus.setMessage("failure");
			}
		}else {
			serviceStatus.setStatus("failure");
			serviceStatus.setMessage("invalid payload");
		}
		return serviceStatus;
	}
	
	
@RequestMapping(value="/getMaintEntityByLEAndUser/{legalEntityCode}/{userId}/{levelCode}",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus getEntityForPlanLevel(@PathVariable("legalEntityCode")Integer legalEntityCode,
			@PathVariable("userId")String userId,@PathVariable("levelCode")String levelCode
			){
		ServiceStatus serviceStatus=new ServiceStatus();		
		if(legalEntityCode!=null && !BankAuditUtil.isEmptyString(userId) && !BankAuditUtil.isEmptyString(levelCode)){
		try {
				List<MaintEntity> maintEntities=maintEntityService.getEntityForPlanLevel(legalEntityCode,userId,levelCode);
			    if(maintEntities!=null&& !maintEntities.isEmpty()){
			    	serviceStatus.setResult(maintEntities);
				    serviceStatus.setStatus("success");
				    serviceStatus.setMessage("successfully retrieved ");	
			    }else {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("MaintEntity not found");
				}
				
			} catch (Exception e) {
				e.printStackTrace();
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("failure");
			}
			
		}else {
			serviceStatus.setStatus("failure");
			serviceStatus.setMessage("invalid payload ");
		}
		
		return serviceStatus;
	}
	
}
