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


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


@RestController

@RequestMapping("/api/entityLevelCodeDesc")
public class EntityLevelCodeDescController {

	
	/**
	 * The entity level code desc service is autowired and make methods
	 * available from service layer .
	 */
	@Autowired
	EntityLevelCodeDescService entityLevelCodeDescService;
	
	/**
	 * The maint legal entity service is autowired and make methods available
	 * from service layer .
	 */
	@Autowired
	MaintLegalEntityService maintLegalEntityService;
	
	/**
	 * 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(EntityLevelCodeDescController.class);
	
	/**
	 * This method is use to Creates the entity level code desc.
	 *
	 * @param entityLevelCodeDesc
	 *            specify the entity level code desc
	 * @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 createEntityLevelCodeDesc(@RequestBody EntityLevelCodeDesc entityLevelCodeDesc ){
		
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(entityLevelCodeDesc!=null
			&& entityLevelCodeDesc.getLegalEntityCode()!=null
			&& !BankAuditUtil.isEmptyString(entityLevelCodeDesc.getLevelCode())
			&& !BankAuditUtil.isEmptyString(entityLevelCodeDesc.getLevelDesc())
			&& !BankAuditUtil.isEmptyString(entityLevelCodeDesc.getMaker())
			&& !BankAuditUtil.isEmptyString(entityLevelCodeDesc.getStatus())
				){
			try {
				
			entityLevelCodeDesc.setSysdateTimestamp(new Timestamp(System.currentTimeMillis()));
			entityLevelCodeDesc.setBusinessdateTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(entityLevelCodeDesc.getLegalEntityCode()));
			entityLevelCodeDesc.setMakerTimestamp(entityLevelCodeDesc.getBusinessdateTimestamp());
			
			MaintLegalEntity maintLegalEntity=maintLegalEntityService.getMaintLegalEntityById(entityLevelCodeDesc.getLegalEntityCode());
			
			if(entityLevelCodeDescService.getEntityLevelCodeDescCount(entityLevelCodeDesc.getLegalEntityCode())<maintLegalEntity.getNumberOfLevels()){
				entityLevelCodeDescService.createEntityLevelCodeDesc(entityLevelCodeDesc);
				serviceStatus.setStatus("success");
				serviceStatus.setMessage("successfully created");
			}else{
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("number of levels limit exceed");
			}
				
			} 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;
	}
	
	/**
	 * This method is use to Update entity level code desc.
	 *
	 * @param entityLevelCodeDesc
	 *            specify the entity level code desc
	 * @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 updateEntityLevelCodeDesc(@RequestBody EntityLevelCodeDesc entityLevelCodeDesc ){
		
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(entityLevelCodeDesc!=null
			&& entityLevelCodeDesc.getLegalEntityCode()!=null
			&& !BankAuditUtil.isEmptyString(entityLevelCodeDesc.getLevelCode())
			&& !BankAuditUtil.isEmptyString(entityLevelCodeDesc.getLevelDesc())
			&& !BankAuditUtil.isEmptyString(entityLevelCodeDesc.getStatus())
				){
			try {
				
			entityLevelCodeDesc.setSysdateTimestamp(new Timestamp(System.currentTimeMillis()));
			entityLevelCodeDesc.setBusinessdateTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(entityLevelCodeDesc.getLegalEntityCode()));
			if(entityLevelCodeDesc.getStatus().equals(BankAuditConstant.STATUS_AUTH)){
				entityLevelCodeDesc.setCheckerTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(entityLevelCodeDesc.getLegalEntityCode()));
			}else{
				entityLevelCodeDesc.setMakerTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(entityLevelCodeDesc.getLegalEntityCode()));
			}
			entityLevelCodeDescService.updateEntityLevelCodeDesc(entityLevelCodeDesc);
			
			serviceStatus.setStatus("success");
			serviceStatus.setMessage("successfully updated");

			} 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;
	}
	
	/**
	 * This method is use to Gets the entity level code desc 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 getEntityLevelCodeDescByLegalEntityCode(@PathVariable("legalEntityCode")Integer legalEntityCode){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(legalEntityCode!=null){
			try {
				
				List<EntityLevelCodeDesc> entityLevelCodeDescs=entityLevelCodeDescService.getEntityLevelCodeDescByLegalEntityCode(legalEntityCode);
				if(entityLevelCodeDescs!=null && !entityLevelCodeDescs.isEmpty()){
					
					serviceStatus.setStatus("success");
					serviceStatus.setResult(entityLevelCodeDescs);
					serviceStatus.setMessage("successfully retieved ");
					
				}else {
					serviceStatus.setMessage("no entityLevelCodeDescs found with legalEntityCode");
					serviceStatus.setStatus("failure");
				}
				
			} catch (Exception e) {
				e.printStackTrace();
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("failure");
			}
		}else {
			serviceStatus.setStatus("failure");
			serviceStatus.setMessage("invalid legalEntityCode ");
		}
		
		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
	 * @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){
		
		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 =  entityLevelCodeDescService.getEntityLevelCodeDesc(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 entity level code desc by legal entity
	 * code and level code.
	 *
	 * @param legalEntityCode
	 *            specify the legal entity code
	 * @param levelCode
	 *            specify the level code
	 * @param status
	 *            specify the status
	 * @return the service status class object with response status and payload
	 *         .
	 */
	
@RequestMapping(value="/getByLegalEntityCodeAndLevelCode/{legalEntityCode}/{levelCode}/{status}",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus getEntityLevelCodeDescByLegalEntityCodeAndLevelCode(
			@PathVariable("legalEntityCode")Integer legalEntityCode,
			@PathVariable("levelCode")String levelCode,
			@PathVariable("status")String status){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(legalEntityCode!=null
				&& !BankAuditUtil.isEmptyString(levelCode)){
			try {
				
				EntityLevelCodeDesc entityLevelCodeDesc=entityLevelCodeDescService.getEntityLevelCodeDescByLegalEntityCodeAndLevelCode(legalEntityCode,levelCode,status);
				if(entityLevelCodeDesc!=null){
					
					serviceStatus.setStatus("success");
					serviceStatus.setResult(entityLevelCodeDesc);
					serviceStatus.setMessage("successfully retieved ");
					
				}else {
					serviceStatus.setMessage("no entityLevelCodeDescs found with legalEntityCode");
					serviceStatus.setStatus("failure");
				}
				
			} catch (Exception e) {
				e.printStackTrace();
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("failure");
			}
		}else {
			serviceStatus.setStatus("failure");
			serviceStatus.setMessage("invalid legalEntityCode ");
		}
		
		return serviceStatus;
	}
	
	
@RequestMapping(value="/deleteEntityLevelCodeDesc/{legalEntityCode}/{levelCode}/{status}",method=RequestMethod.DELETE,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus deleteEntityLevelCodeDesc(
			@PathVariable("legalEntityCode")Integer legalEntityCode,
			@PathVariable("levelCode")String levelCode,
			@PathVariable("status")String status){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(legalEntityCode!=null
				&& !BankAuditUtil.isEmptyString(levelCode)){
			try {				
				 entityLevelCodeDescService.deleteEntityLevelCodeDesc(legalEntityCode,levelCode,status);	
				 serviceStatus.setStatus("success"); 
			     serviceStatus.setMessage("successfully deleted the rejected record ");					
			} catch (Exception e) {
				e.printStackTrace();
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("failure");
			}
		}else {
			serviceStatus.setStatus("failure");
			serviceStatus.setMessage("invalid legalEntityCode ");
		}
		
		return serviceStatus;
	}
	
	/** To get the Entity level **/
	
@RequestMapping(value="/getEntityLevelCodesDescByUserID/{legalEntityCode}/{userId}",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus getEntityLevelCodesDescByUserID(@PathVariable("legalEntityCode")Integer legalEntityCode,
			@PathVariable("userId")String userId){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(legalEntityCode!=null){
			try {
				
				List<EntityLevelCodeDesc> entityLevelCodeDescs=entityLevelCodeDescService.getEntityLevelCodesDescByUserID(legalEntityCode,userId);
				if(entityLevelCodeDescs!=null && !entityLevelCodeDescs.isEmpty()){
					
					serviceStatus.setStatus("success");
					serviceStatus.setResult(entityLevelCodeDescs);
					serviceStatus.setMessage("successfully retieved ");
					
				}else {
					serviceStatus.setMessage("no entityLevelCodeDescs found with legalEntityCode");
					serviceStatus.setStatus("failure");
				}
				
			} catch (Exception e) {
				e.printStackTrace();
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("failure");
			}
		}else {
			serviceStatus.setStatus("failure");
			serviceStatus.setMessage("invalid legalEntityCode ");
		}
		
		return serviceStatus;
	}
	
}
