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

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

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.dto.MaintUsergroupRolesDto;
import com.bankaudit.model.MaintUsergroupRoles;
import com.bankaudit.service.BusinessDateService;
import com.bankaudit.service.MaintUsergroupRolesService;
import com.bankaudit.service.SequenceAppenderService;
import com.bankaudit.service.UserService;
import com.bankaudit.util.BankAuditUtil;
import com.bankaudit.util.ServiceStatus;

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


@RestController

@RequestMapping("/api/maintUsergroupRoles")
public class MaintUsergroupRolesController {


	/**
	 * The maint usergroup roles service is autowired and make methods available
	 * from service layer .
	 */
	@Autowired
	MaintUsergroupRolesService maintUsergroupRolesService;
	
	/**
	 * The business date service is autowired and make methods available from
	 * service layer .
	 */
	@Autowired
	BusinessDateService businessDateService;

	/**
	 * The sequence appender service is autowired and make methods available
	 * from service layer .
	 */
	@Autowired
	SequenceAppenderService sequenceAppenderService;
	
	@Autowired
	UserService userService;
	
	/** The Constant logger is used to specify the . */
	static final Logger logger = Logger.getLogger(MaintUsergroupRolesController.class);
	
	private String functionId="maintUsergroupRoles";
	
	/**
	 * This method is use to Creates the maint usergroup roles.
	 *
	 * @param maintUsergroupRolesDto
	 *            specify the maint usergroup roles dto
	 * @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 createMaintUsergroupRoles(@RequestBody MaintUsergroupRolesDto maintUsergroupRolesDto){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(maintUsergroupRolesDto!=null 
				&& maintUsergroupRolesDto.getMaintUsergroupRolesWrk()!=null
				&& !BankAuditUtil.isEmptyString(maintUsergroupRolesDto.getMaintUsergroupRolesWrk().getUgRoleName())
				&& !BankAuditUtil.isEmptyString(maintUsergroupRolesDto.getMaintUsergroupRolesWrk().getUgRoleCode())
				&& !BankAuditUtil.isEmptyString(maintUsergroupRolesDto.getMaintUsergroupRolesWrk().getMaker())
				){ 
		
			try {
			    maintUsergroupRolesDto.getMaintUsergroupRolesWrk().setBusinessdateTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(maintUsergroupRolesDto.getMaintUsergroupRolesWrk().getLegalEntityCode()));
			    maintUsergroupRolesDto.getMaintUsergroupRolesWrk().setSysdateTimestamp(new Timestamp(System.currentTimeMillis()));
			    maintUsergroupRolesDto.getMaintUsergroupRolesWrk().setMakerTimestamp(maintUsergroupRolesDto.getMaintUsergroupRolesWrk().getBusinessdateTimestamp());
			    
			    maintUsergroupRolesService.createMaintUsergroupRoles(maintUsergroupRolesDto);
			    
			    serviceStatus.setStatus("success");
			    serviceStatus.setMessage("successfully created");
			} catch (Exception e) {
				serviceStatus.setStatus("failure");
				if(e instanceof org.springframework.dao.DataIntegrityViolationException) {
					serviceStatus.setMessage("DATAINTGRTY_VIOLATION");
				}else serviceStatus.setMessage("EXCP_OCCURED");
			}
			
		}else {
			serviceStatus.setStatus("failure");
			serviceStatus.setMessage("invalid payload ");
		}
		
		return serviceStatus;
	}
	
	/**
	 * This method is use to Update maint usergroup roles.
	 *
	 * @param maintUsergroupRolesDto
	 *            specify the maint usergroup roles dto
	 * @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 updateMaintUsergroupRoles(@RequestBody MaintUsergroupRolesDto maintUsergroupRolesDto){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(maintUsergroupRolesDto!=null 
				&& maintUsergroupRolesDto.getMaintUsergroupRolesWrk()!=null
				&& !BankAuditUtil.isEmptyString(maintUsergroupRolesDto.getMaintUsergroupRolesWrk().getUgRoleName())
				&& !BankAuditUtil.isEmptyString(maintUsergroupRolesDto.getMaintUsergroupRolesWrk().getUgRoleCode())
				&& !BankAuditUtil.isEmptyString(maintUsergroupRolesDto.getMaintUsergroupRolesWrk().getMaker())
				){
			try {
				maintUsergroupRolesDto.getMaintUsergroupRolesWrk().setBusinessdateTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(maintUsergroupRolesDto.getMaintUsergroupRolesWrk().getLegalEntityCode()));
				maintUsergroupRolesDto.getMaintUsergroupRolesWrk().setSysdateTimestamp(new Timestamp(System.currentTimeMillis()));
				maintUsergroupRolesDto.getMaintUsergroupRolesWrk().setMakerTimestamp(maintUsergroupRolesDto.getMaintUsergroupRolesWrk().getBusinessdateTimestamp());
				   
				maintUsergroupRolesService.updateMaintUsergroupRoles(maintUsergroupRolesDto);
				    
				    serviceStatus.setStatus("success");
				    serviceStatus.setMessage("successfully updated");
			
			} catch (Exception e) {
				serviceStatus.setStatus("failure");
				if(e instanceof org.springframework.dao.DataIntegrityViolationException) {
					serviceStatus.setMessage("DATAINTGRTY_VIOLATION");
				}else serviceStatus.setMessage("EXCP_OCCURED");
			}
			
		}else {
			serviceStatus.setStatus("failure");
			serviceStatus.setMessage("invalid payload ");
		}
		
		return serviceStatus;
	}
	
	/**
	 * This method is use to Gets the maint usergroup role.
	 *
	 * @param legalEntityCode
	 *            specify the legal entity code
	 * @param ugRoleCode
	 *            specify the ug role code
	 * @param status
	 *            specify the status
	 * @return the service status class object with response status and payload
	 *         .
	 */
	
@RequestMapping(value="/getByLegalEntityCodeAndUgRoleCode/{legalEntityCode}/{ugRoleCode}/{status}/{userId}/{role}",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus getMaintUsergroupRole(@PathVariable("legalEntityCode")Integer legalEntityCode,
			@PathVariable("ugRoleCode") String ugRoleCode,
			@PathVariable("status") String status,
			@PathVariable("userId") String loginUserId,  // login User id
			@PathVariable(required=false,value="role") String loginUserrole	){  // login user role
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(legalEntityCode!=null && !BankAuditUtil.isEmptyString(ugRoleCode)
				&& !BankAuditUtil.isEmptyString(status)){
			
			try {
				logger.info("Inside getByLegalEntityCodeAndUgRoleCode legalEntityCode:: "+legalEntityCode +" loginUserId:: "+ loginUserId+" loginUserrole:: "+loginUserrole);
				boolean validUsrforRole=userService.isUserHavingEntitlement(legalEntityCode, loginUserId, loginUserrole, functionId, "getByLegalEntityCodeAndUgRoleCode");
				
				if(validUsrforRole) {					
					MaintUsergroupRoles maintUsergroupRole=maintUsergroupRolesService.getMaintUsergroupRole(legalEntityCode,ugRoleCode,status);
				    if(maintUsergroupRole!=null){
				    	serviceStatus.setResult(maintUsergroupRole);
					    serviceStatus.setStatus("success");
					    serviceStatus.setMessage("successfully retrieved ");	
				    }else {
						serviceStatus.setStatus("failure");
						serviceStatus.setMessage("ugRole not found");
					}
				}else {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("User is not entitled for this Role ");
				}				
			} 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 maint usergroup roles.
	 *
	 * @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 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 getMaintUsergroupRoles(
			@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("userId")String userId){
		
		DataTableResponse dataTableResponse=null;
		
		if(!BankAuditUtil.isEmptyString(drawStr)
				&& !BankAuditUtil.isEmptyString(length)
				&& !BankAuditUtil.isEmptyString(start)
				&& !BankAuditUtil.isEmptyString(legalEntityCodeStr)
				&&  !BankAuditUtil.isEmptyString(userId)){
			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 = maintUsergroupRolesService.getMaintUsergroupRoles(legalEntityCode,userId,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 usergroup roles by legal entity code
	 * and user id.
	 *
	 * @param legalEntityCode
	 *            specify the legal entity code
	 * @param userId
	 *            specify the user id
	 * @param status
	 *            specify the status
	 * @return the service status class object with response status and payload
	 *         .
	 */
	
@RequestMapping(value="/getByLegalEntityCodeAndUserId/{legalEntityCode}/{userId}/{status}/{loginUserId}/{role}",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus getMaintUsergroupRolesByLegalEntityCodeAndUserId(@PathVariable("legalEntityCode")Integer legalEntityCode,
			@PathVariable("userId") String userId,
			@PathVariable("status") String status,
			@PathVariable(required=false,value="loginUserId") String loginUserId,
			@PathVariable(required=false,value="role") String role	){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(legalEntityCode!=null && !BankAuditUtil.isEmptyString(userId)){
			
			try {
				logger.info("Inside getByLegalEntityCodeAndUserId legalEntityCode:: "+legalEntityCode +" loginUserId:: "+ loginUserId+" role:: "+role);
				
				boolean validUsrforRole=userService.isUserHavingEntitlement(legalEntityCode, loginUserId, role, functionId, "getByLegalEntityCodeAndUserId");
				if(validUsrforRole) {
				    Set<MaintUsergroupRoles> maintUsergroupRoles=maintUsergroupRolesService.getMaintUsergroupRolesByLegalEntityCodeAndUserId(legalEntityCode,userId,status);
				    if(maintUsergroupRoles!=null && !maintUsergroupRoles.isEmpty()){
				    	serviceStatus.setResult(maintUsergroupRoles);
					    serviceStatus.setStatus("success");
					    serviceStatus.setMessage("successfully retrieved ");	
				    }else {
						serviceStatus.setStatus("failure");
						serviceStatus.setMessage("ugRole not found");
					}
				}else {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("User is not entitled for this Role ");
				}
			} 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 maint usergroup roles by legal entity
	 * code.
	 *
	 * @param legalEntityCode
	 *            specify the legal entity code
	 * @param status
	 *            specify the status
	 * @return the service status class object with response status and payload
	 *         .
	 */
	
@RequestMapping(value="/getByLegalEntityCode/{legalEntityCode}/{status}/{userId}/{role}",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus getMaintUsergroupRolesByLegalEntityCode(@PathVariable("legalEntityCode")Integer legalEntityCode,
			@PathVariable("status") String status,
			@PathVariable("userId")String loginUserId,
			@PathVariable(required=false,value="role") String role	){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(legalEntityCode!=null && !BankAuditUtil.isEmptyString(status)){
			
			try {
				logger.info("Inside getByLegalEntityCode legalEntityCode:: "+legalEntityCode +" loginUserId:: "+ loginUserId+" role:: "+role);
				
				boolean validUsrforRole=userService.isUserHavingEntitlement(legalEntityCode, loginUserId, role, functionId, "getByLegalEntityCode");
				if(validUsrforRole) {
				    List maintUsergroupRoles=maintUsergroupRolesService.getMaintUsergroupRolesByLegalEntityCodeAndUserId(legalEntityCode,status);
				    if(maintUsergroupRoles!=null && !maintUsergroupRoles.isEmpty()){
				    	serviceStatus.setResult(maintUsergroupRoles);
					    serviceStatus.setStatus("success");
					    serviceStatus.setMessage("successfully retrieved ");	
				    }else {
						serviceStatus.setStatus("failure");
						serviceStatus.setMessage("ugRole not found");
					}
				}else {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("User is not entitled for this Role ");
				}
				    
			} 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 maint usergroup roles by legal entity
	 * code.
	 *
	 * @param legalEntityCode
	 *            specify the legal entity code
	 * @param status
	 *            specify the status
	 * @return the service status class object with response status and payload
	 *         .
	 */
	
@RequestMapping(value="/getTotalUsersPerRole/{legalEntityCode}",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus getTotalUsersPerRole(@PathVariable("legalEntityCode")Integer legalEntityCode
			){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(legalEntityCode!=null){
			
			try {
			    List<Map<String,Integer>> maintUsergroupRoles=maintUsergroupRolesService.getTotalUsersPerRole(legalEntityCode);
			    if(maintUsergroupRoles!=null && !maintUsergroupRoles.isEmpty()){
			    	serviceStatus.setResult(maintUsergroupRoles);
				    serviceStatus.setStatus("success");
				    serviceStatus.setMessage("successfully retrieved ");	
			    }else {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("ugRole not found");
				}
				
			} catch (Exception e) {
				e.printStackTrace();
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("failure");
			}
			
		}else {
			serviceStatus.setStatus("failure");
			serviceStatus.setMessage("invalid payload ");
		}
		
		return serviceStatus;
	}
	
}
