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

import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;

import org.jboss.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
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.ChangePasswordDto;
import com.bankaudit.dto.DataTableResponse;
import com.bankaudit.dto.LoginRequest;
import com.bankaudit.dto.UpdateTokenDetailsRequest;
import com.bankaudit.dto.UserRegistrationDto;
import com.bankaudit.model.GeneralParameter;
import com.bankaudit.model.User;
import com.bankaudit.model.UserResetPassword;
import com.bankaudit.model.UserWrk;
import com.bankaudit.rest.process.service.EmailService;
import com.bankaudit.security.CustomUserDetails;
import com.bankaudit.service.BusinessDateService;
import com.bankaudit.service.GeneralParameterService;
import com.bankaudit.service.MaintEntityService;
import com.bankaudit.service.MaintUsergroupRolesService;
import com.bankaudit.service.UserResetPasswordService;
import com.bankaudit.service.UserService;
import com.bankaudit.util.BankAuditUtil;
import com.bankaudit.util.ServiceStatus;
import com.bankaudit.util.VerifyRecaptcha;

/**
 * {@link UserController} class provides the user management and check session services end-points .
 *
 * @author amit.patel
 * @version 1.0
 */


@RestController

@RequestMapping("/api/user")
public class UserController {

	/**
	 * The user service is autowired and make methods available from service
	 * layer .
	 */
	@Autowired
	private UserService userService;
	
	

	/**
	 * The User Reset Password  service is autowired and make methods available from service
	 * layer .
	 */
	@Autowired 
	UserResetPasswordService userResetPasswordService;
	

	
	/**
	 * The business date service is autowired and make methods available from
	 * service layer .
	 */
	@Autowired
	BusinessDateService businessDateService;
	
	/**
	 * The password encoder is autowired and make methods available from service
	 * layer .
	 */
	@Autowired
	PasswordEncoder passwordEncoder;
	
	/**
	 * The general parameter service is autowired and make methods available
	 * from service layer .
	 */
	@Autowired
	GeneralParameterService generalParameterService;
	
	/**
	 * The maint usergroup roles service is autowired and make methods available
	 * from service layer .
	 */
	@Autowired 
	MaintUsergroupRolesService maintUsergroupRolesService;
	
	@Autowired
	MaintEntityService maintEntityService;
	
	@Autowired 
	EmailService emailService;
	
	
	/** The Constant logger is used to specify the . */
	static final Logger logger = Logger.getLogger(UserController.class);
	
	private VerifyRecaptcha verifyRecaptcha;
	
	private String functionId="USER";
	
	
	
	@GetMapping("/healthCheck")
	public ResponseEntity<String> healthCheck() {
		return ResponseEntity.ok("Service is alive");
	}

	
	
	@PostMapping(value = "/login", produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<ServiceStatus> login(@RequestHeader(value = "Host", required = false) String domain,
			@RequestBody LoginRequest loginRequest) {
		return userService.login(domain, loginRequest);
	}

	
	
	@PostMapping(value = "/updateTokenDetails", produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<ServiceStatus> updateTokenDetails(@RequestHeader(value = "Authorization", required = false) String authorizationHeader,
			@RequestBody UpdateTokenDetailsRequest updateTokenDetailsRequest) {
		return userService.updateTokenDetails(authorizationHeader, updateTokenDetailsRequest);
	}

	
	
	@PostMapping(value = "/logout", produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<ServiceStatus> logout(@RequestHeader(value = "Authorization", required = false) String authorizationHeader) {
		return userService.logout(authorizationHeader);
	}

	
	
	@PostMapping(value = "/getUserRolesAndDetails", produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<ServiceStatus> getUserRolesAndDetails(@RequestHeader(value = "Authorization", required = false) String authorizationHeader) {
		return userService.getUserRolesAndDetails(authorizationHeader);
	}

	
	
	@RequestMapping(method=RequestMethod.POST,consumes=MediaType.APPLICATION_JSON_VALUE,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus createUser(@RequestBody UserRegistrationDto userRegistrationDto,
			@RequestParam(required=false,value="legalEntityCode")String legalEntityCodeStr,
			@RequestParam(required=false,value="userCode")String userId,
			@RequestParam(required=false,value="role") String role){
		
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(userRegistrationDto!=null
				&& userRegistrationDto.getUserWrk()!=null
				&& userRegistrationDto.getUserWrk().getLegalEntityCode()!=null
				&& BankAuditUtil.isNumber(userRegistrationDto.getUserWrk().getMobile1()) 
				&& BankAuditUtil.isNumber(userRegistrationDto.getUserWrk().getMobile2()) 
				&& BankAuditUtil.isNumber(userRegistrationDto.getUserWrk().getLandline1())
				// all validations required 
				){
			try {
				logger.info("Inside User createUser() ..");
				boolean validUsrforRole=userService.isUserHavingEntitlement(Integer.parseInt(legalEntityCodeStr), userId, role, functionId, "CREATE"); // To validate if the User having the particular role for VAPT (Broken access control)
				if(validUsrforRole) {
					userRegistrationDto.getUserWrk().setSysdateTimestamp(new Timestamp(System.currentTimeMillis()));
					userRegistrationDto.getUserWrk().setBusinessdateTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(userRegistrationDto.getUserWrk().getLegalEntityCode()));
					userRegistrationDto.getUserWrk().setMakerTimestamp(userRegistrationDto.getUserWrk().getBusinessdateTimestamp());
					
					List<GeneralParameter> generalParameters=generalParameterService.getGeneralParameter(userRegistrationDto.getUserWrk().getLegalEntityCode(), null, null, BankAuditConstant.GP_DEFAULT_PASS,null, null, null);
					if(generalParameters!=null && !generalParameters.isEmpty()){
						userRegistrationDto.getUserWrk().setPassword(passwordEncoder.encode(generalParameters.get(0).getValue()));
						userService.createUser(userRegistrationDto);
						serviceStatus.setStatus("success");
						serviceStatus.setMessage("successfully registered");	
					}else {
						serviceStatus.setStatus("failure");
						serviceStatus.setMessage("default password not present in db");
					}
				}else {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("User is not entitled for this Role ");
				}
			} 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 user payload");
		}		
		return serviceStatus;
	}
	
	/**
	 * This method is use to Gets the user.
	 *
	 * @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 getUser(
			@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,
			@RequestParam(required=false,value="role") String role){
		
		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);
				}
				boolean validUsrforRole=userService.isUserHavingEntitlement(legalEntityCode, userId, role, functionId, "GETALL"); // To validate if the User having the particular role for VAPT (Broken access control)
				if(validUsrforRole) {
					dataTableResponse = userService.getUser(legalEntityCode,userId,search,orderColumn,orderDirection,page,size);
					dataTableResponse.setDraw(draw);    
				}else {
					dataTableResponse=new DataTableResponse();
	                dataTableResponse.setError("User is not entitled for this Role ");
				}
			} 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 user.
	 *
	 * @param legalEntityCodeStr
	 *            specify the legal entity code str
	 * @param unitCode
	 *            specify the unit 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="/get",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE) 
	ServiceStatus getUser(
			@RequestParam("legalEntityCode")String legalEntityCodeStr,
			@RequestParam(required=false,value="unitCode") String unitCode,
			@RequestParam(required=false,value="userCode") String userId,
			@RequestParam(value="status") String status
			){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		
		if(!BankAuditUtil.isEmptyString(legalEntityCodeStr)){
			try {
				Integer legalEntityCode=Integer.parseInt(legalEntityCodeStr);
				List<User> users = userService.getUser(legalEntityCode,unitCode,userId,status);
				if(users!=null && !users.isEmpty()){
					serviceStatus.setStatus("success");
					serviceStatus.setMessage("successfuly retrieved");
					serviceStatus.setResult(users);
				} else {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("no records found");
				}
					
			} catch (Exception e) {
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("failure");
				e.printStackTrace();
			}
		
		}else {
			serviceStatus.setStatus("failure");
			serviceStatus.setMessage("legalEntityCode required");
		}
		
		
		return serviceStatus;
	}

	
	
	
	
	
	/**
	 * This method is use to Update user.
	 *
	 * @param userRegistrationDto
	 *            specify the user registration 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 updateUser(@RequestBody UserRegistrationDto userRegistrationDto,
			@RequestParam(required=false,value="legalEntityCode")String legalEntityCodeStr,
			@RequestParam(required=false,value="userCode")String userId,
			@RequestParam(required=false,value="role") String role){
		
		ServiceStatus serviceStatus=new ServiceStatus();
		 logger.info("updateUser .. "+ userRegistrationDto.getUserWrk().getMobile1() +" M2.. "+userRegistrationDto.getUserWrk().getMobile2() +" L1.. "+userRegistrationDto.getUserWrk().getLandline1());
		if(userRegistrationDto!=null
				&& userRegistrationDto.getUserWrk()!=null
                && userRegistrationDto.getUserWrk().getLegalEntityCode()!=null
                && !BankAuditUtil.isEmptyString(userRegistrationDto.getUserWrk().getUserId())
                && BankAuditUtil.isNumber(userRegistrationDto.getUserWrk().getMobile1()) 
				&& BankAuditUtil.isNumber(userRegistrationDto.getUserWrk().getMobile2()) 
				&& BankAuditUtil.isNumber(userRegistrationDto.getUserWrk().getLandline1())
				){
			try {
				boolean validUsrforRole=userService.isUserHavingEntitlement(Integer.parseInt(legalEntityCodeStr), userId, role, functionId, "UPDATE"); // To validate if the User having the particular role for VAPT (Broken access control)
				if(validUsrforRole) {
					UserWrk user=userRegistrationDto.getUserWrk();
					user.setSysdateTimestamp(new Timestamp(System.currentTimeMillis()));
					user.setBusinessdateTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(user.getLegalEntityCode()));
					if(userRegistrationDto.getUserWrk().getEntityStatus().equalsIgnoreCase("A")) userRegistrationDto.getUserWrk().setUnsuccessfulAttempts(0);
					if(user.getStatus().equals(BankAuditConstant.STATUS_AUTH)){
						user.setCheckerTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(user.getLegalEntityCode()));
					}else{
						user.setMakerTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(user.getLegalEntityCode()));
					}	
						List<GeneralParameter> generalParameters=generalParameterService.getGeneralParameter(userRegistrationDto.getUserWrk().getLegalEntityCode(), null, null, BankAuditConstant.GP_DEFAULT_PASS,null, null, null);
						if(generalParameters!=null && !generalParameters.isEmpty()){
							userRegistrationDto.getUserWrk().setPassword(passwordEncoder.encode(generalParameters.get(0).getValue()));
							userService.updateUser(userRegistrationDto);
							serviceStatus.setStatus("success");
							serviceStatus.setMessage("successfully registered");	
						}else {
							serviceStatus.setStatus("failure");
							serviceStatus.setMessage("default password not present in db");
						}
						serviceStatus.setStatus("success");
						serviceStatus.setMessage("successfully updated");
				}else {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("User is not entitled for this Role ");
				}
			} 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 user payload");
		}
		
		return serviceStatus;
	}
	
	
	/**
	 * This method is use to Checks if is user.
	 *
	 * @param legalEntityCode
	 *            specify the legal entity code
	 * @param userId
	 *            specify the user id
	 * @return the service status class object with response status and payload
	 *         .
	 */
	
@RequestMapping(value="/isUser/{legalEntityCode}/{userId}",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus isUser(@PathVariable("legalEntityCode")Integer legalEntityCode,
			@PathVariable("userId") String userId
			){
		ServiceStatus serviceStatus=new ServiceStatus();
		if(legalEntityCode!=null 
				&& !BankAuditUtil.isEmptyString(userId)
				){
			
			try {
			    Boolean user=userService.isUser(legalEntityCode,userId);
		    	serviceStatus.setResult(user);
			    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="/getUserByRoleId",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE) 
	ServiceStatus getUserByRoleId(
			@RequestParam("legalEntityCode")String legalEntityCodeStr,
			@RequestParam(required=false,value="userRoleId") String userRoleId
			){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		
		if(!BankAuditUtil.isEmptyString(legalEntityCodeStr)){
			try {
				Integer legalEntityCode=Integer.parseInt(legalEntityCodeStr);
				List<User> users = userService.getUserByRoleId(legalEntityCode,userRoleId);
				if(users!=null && !users.isEmpty()){
					serviceStatus.setStatus("success");
					serviceStatus.setMessage("successfuly retrieved");
					serviceStatus.setResult(users);
				} else {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("no records found");
				}
					
			} catch (Exception e) {
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("failure");
				e.printStackTrace();
			}
		
		}else {
			serviceStatus.setStatus("failure");
			serviceStatus.setMessage("legalEntityCode required");
		}
		
		
		return serviceStatus;
	}
	
	
@RequestMapping(value="/file/upload/tables",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE) 
	Object getUploadTables(){
		
		Authentication auth = SecurityContextHolder.getContext().getAuthentication();
	     Object object= auth.getPrincipal();
	     Integer legalEntityCode;
	     Map<String, String> response;
	     if(object instanceof UserDetails){
	    	 legalEntityCode=((CustomUserDetails) object).getLegalEntityCode();
	    	 return userService.getUploadTables(legalEntityCode);
	     }else{
	    	 response=new HashMap<>();
	    	 response.put("invalid_token", "please login again.");
	    	 return response;
	     }


		
	}
	
	/**
	 * This method is use to Reset the user password.
	 *
	 * @param changePasswordDto
	 *            specify the user changepassword dto
	 * @return the service status class object with response status and payload
	 *         .
	 */
	
@RequestMapping(value="/getEmailIdforResetPassword",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus getEmailIdforResetPassword(@RequestParam("legalEntityCode")String legalEntityCodeStr,
			@RequestParam("userId") String userId){
		
		ServiceStatus serviceStatus=new ServiceStatus();
		String emailId=null;
		ChangePasswordDto changePasswordDto= new ChangePasswordDto();
		logger.info("getEmailIdforResetPassword .."+legalEntityCodeStr+" userId .. "+ userId);
		if(!BankAuditUtil.isEmptyString(legalEntityCodeStr) && !BankAuditUtil.isEmptyString(userId)){
			try {
				Integer legalEntityCode=Integer.parseInt(legalEntityCodeStr);
				emailId=userResetPasswordService.getEmailIdforResetPassword(legalEntityCode,userId);
				logger.info("inside getEmailIdforResetPassword emailId .."+emailId);
				changePasswordDto.setLegalEntityCode(legalEntityCode);
				changePasswordDto.setUserId(userId);
				if(emailId != null && !emailId.equalsIgnoreCase("NoEmail") &&  !emailId.equalsIgnoreCase("InvalidUser")) {
					changePasswordDto.setEmail(emailId);
					serviceStatus.setResult(changePasswordDto);
					serviceStatus.setStatus("success");
					serviceStatus.setMessage("successfully Retrieved");	
				}else {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage(emailId);	
				}
				
			} catch (Exception e) {
				e.printStackTrace();
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("failure");
			}
		}else {
			serviceStatus.setStatus("failure");
			serviceStatus.setMessage("invalid user payload");
		}
		
		return serviceStatus;
	}
	
	/**
	 * This method is use to Validate the User, Make an entry into UserResetPassword table and Sending Email to the User for Password Reset.
	 *
	 * @param legalEntityCodeStr
	 *            specify the legal entity code str
	 * @param userId
	 *            specify the user id
	 * @param emailId
	 *            specify the emailId
	 * @param status
	 *            specify the status
	 * @return the service status class object with response status and payload
	 *         .
	 */
	
@RequestMapping(value="/validateUser",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE) 
	ServiceStatus validateUser(
			@RequestParam("legalEntityCode")String legalEntityCodeStr,
			@RequestParam(value="userId") String userId,
			@RequestParam(value="emailId") String emailId,
			@RequestParam(value="status") String status			
			){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		
		if(!BankAuditUtil.isEmptyString(legalEntityCodeStr)){
			try {
				Integer legalEntityCode=Integer.parseInt(legalEntityCodeStr);
							
				List<User> users = userService.validateUser(legalEntityCode,emailId,userId,status); 
				if(users!=null && !users.isEmpty()){
					UserResetPassword userResetPassword = null;
					try {
						userResetPassword = userResetPasswordService.createUserResetPassword(legalEntityCode,userId);
					    userResetPasswordService.sendEmail(emailId,userResetPassword.getToken());
					}catch (Exception e) {
						serviceStatus.setStatus("failure");
						serviceStatus.setMessage("Unable to genetare Token,Please contact Admin.");
					}
					
					serviceStatus.setStatus("success");
					serviceStatus.setMessage("successfuly retrieved");
					serviceStatus.setResult(users);
					//Trigger a mail with token.	
					
				} else {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("Not a valied USER, Please check given USER-ID (or) EMAIL-ADDRESS.");
				}
				
			} catch (Exception e) {
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("failure");
				e.printStackTrace();
			}
		
		}else {
			serviceStatus.setStatus("failure");
			serviceStatus.setMessage("invalid payload");
		}
		return serviceStatus;
	}
	
	/**
	 * This method is use to Reset the user password.
	 *
	 * @param changePasswordDto
	 *            specify the user changepassword dto
	 * @return the service status class object with response status and payload
	 *         .
	 */
	
@RequestMapping(value="/resetPassword", method=RequestMethod.PUT,consumes=MediaType.APPLICATION_JSON_VALUE,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus resetPassword(@RequestBody ChangePasswordDto changePasswordDto){
		
		ServiceStatus serviceStatus=new ServiceStatus();
		String validate="valid";
		if(changePasswordDto!=null
				&& changePasswordDto.getUserId()!=null
                && changePasswordDto.getLegalEntityCode()!=null
                ){
			try {
				validate=userResetPasswordService.validateLink(changePasswordDto);
				logger.info("inside resetPassword validate .."+validate);
				if(validate.equals("valid")) {
					changePasswordDto.setSysdateTimestamp(new Timestamp(System.currentTimeMillis()));
					changePasswordDto.setBusinessdateTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(changePasswordDto.getLegalEntityCode()));
					//PasswordEncoder passwordEncoder=new BCryptPasswordEncoder();
					changePasswordDto.setNewPassword(passwordEncoder.encode(changePasswordDto.getNewPassword()));
					userResetPasswordService.resetPassword(changePasswordDto);
					serviceStatus.setStatus("success");
					serviceStatus.setMessage("successfully validated and updated");	
				}else {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage(validate);	
				}
				
			} 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 user payload");
		}
		
		return serviceStatus;
	}
	
	
	
@RequestMapping(value="/getAllActiveUsers",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE) 
	ServiceStatus getAllActiveUsers(
			@RequestParam("legalEntityCode")String legalEntityCodeStr,
			@RequestParam(required=false,value="unitCode") String unitCode,
			@RequestParam(value="status") String status
			){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		
		if(!BankAuditUtil.isEmptyString(legalEntityCodeStr)){
			try {
				Integer legalEntityCode=Integer.parseInt(legalEntityCodeStr);
				List<User> users = userService.getAllActiveUsers(legalEntityCode,unitCode,status);
				if(users!=null && !users.isEmpty()){
					serviceStatus.setStatus("success");
					serviceStatus.setMessage("successfuly retrieved");
					serviceStatus.setResult(users);
				} else {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("no records found");
				}
					
			} catch (Exception e) {
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("failure");
				e.printStackTrace();
			}
		
		}else {
			serviceStatus.setStatus("failure");
			serviceStatus.setMessage("legalEntityCode required");
		}
		
		
		return serviceStatus;
	}
	
	
@RequestMapping(value="/validateUserWithIdandMobile",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE) 
	ServiceStatus validateUserWithIdandMobile(
			@RequestParam("legalEntityCode")String legalEntityCodeStr,
			@RequestParam(required=true,value="userId") String userId,
			@RequestParam(required=true,value="mobile1") String mobile1,
			@RequestParam(required=false,value="emailId") String emailId,
			@RequestParam(required=false,value="status") String status,
			@RequestParam(required=false,value="gRecaptchaResponse") String gRecaptchaResponse
			){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		logger.info("Inside validateUserWithIdandMobile .."+ legalEntityCodeStr + " :: "+userId +" :: "+ mobile1+" :: "+gRecaptchaResponse);
		if(!BankAuditUtil.isEmptyString(legalEntityCodeStr)){
			try {
				Integer legalEntityCode=Integer.parseInt(legalEntityCodeStr);
				boolean verifyCaptcha =true;
				try {
				 	logger.info("gRecaptchaResponse .."+gRecaptchaResponse);
					verifyCaptcha = verifyRecaptcha.verify(gRecaptchaResponse);
					logger.info("verify captcha .. "+ verifyCaptcha);
				}catch(Exception e) {
					e.printStackTrace(System.out);
					verifyCaptcha =true;
				}				
				if(verifyCaptcha){	
					String userStatus = userService.validateUserOrgetUserStatus(legalEntityCode,userId,status); 
					if(userStatus !=null && userStatus.equalsIgnoreCase("A")){
						Boolean valid = userService.validateUserWithIdandMobile(legalEntityCode,userId,mobile1,emailId,status); 
						if(valid){
							//new code for reset password
							
							if(emailId == null || emailId.isEmpty())
								emailId = userResetPasswordService.getEmailIdforResetPassword(legalEntityCode, userId);
							UserResetPassword userResetPassword = userResetPasswordService.createUserResetPassword(legalEntityCode, userId);
							//userResetPasswordService.sendEmail(emailId, userResetPassword.getToken());
							emailService.sendEmailWithTokenForResetPwd(legalEntityCode, emailId, userResetPassword.getToken());
							
							//ended here
							serviceStatus.setStatus("success");
							serviceStatus.setMessage("successfuly retrieved");
						} else {
							serviceStatus.setStatus("failure");
							serviceStatus.setMessage("Not a valid combination, Please check given USER-ID (or) Mobile.");
						}
					} else {
						String userStatusDesc=("I".equalsIgnoreCase(userStatus)? "Inactive" : ("L".equalsIgnoreCase(userStatus)? "Locked": "C".equalsIgnoreCase(userStatus)? "Closed":" not active") );
						serviceStatus.setStatus("failure");
						serviceStatus.setMessage("The Account is "+userStatusDesc +", contact Admin.");
					}
				}else {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("The captcha not verified.");
				}					
			} catch (Exception e) {
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("failure");
				e.printStackTrace();
			}
		
		}else {
			serviceStatus.setStatus("failure");
			serviceStatus.setMessage("invalid payload");
		}
		return serviceStatus;
	}
	
	
@RequestMapping(value="/validateUserOrgetUserStatus",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE) 
	ServiceStatus validateUserOrgetUserStatus(
			@RequestParam("legalEntityCode")String legalEntityCodeStr,
			@RequestParam(required=true,value="userId") String userId,
			@RequestParam(required=false,value="status") String status
			){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		
		if(!BankAuditUtil.isEmptyString(legalEntityCodeStr)){
			try {
				Integer legalEntityCode=Integer.parseInt(legalEntityCodeStr);
				String userStatus = userService.validateUserOrgetUserStatus(legalEntityCode,userId,status); 
				if(userStatus !=null && userStatus.equalsIgnoreCase("A")){
					serviceStatus.setStatus("success");
					serviceStatus.setMessage("successfuly retrieved");
				} else {
					String userStatusDesc=("I".equalsIgnoreCase(userStatus)? "Inactive" : ("L".equalsIgnoreCase(userStatus)? "Locked": "C".equalsIgnoreCase(userStatus)? "Closed":"not active") );
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("The Account is "+userStatusDesc +", contact Admin.");
				}
					
			} catch (Exception e) {
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("failure");
				e.printStackTrace();
			}
		
		}else {
			serviceStatus.setStatus("failure");
			serviceStatus.setMessage("invalid payload");
		}
		return serviceStatus;
	}
	
	/* This method is commented as VAPT issue of "Account Takeover"
	 * 
@RequestMapping(value="/updateUserPassword",method=RequestMethod.PUT,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus updateUserPassword(
			@RequestParam("legalEntityCode")Integer legalEntityCode,
			@RequestParam("userId")String userId,
			@RequestParam("password")String pwd){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		logger.info("Inside Contrlr updateUserPassword ..  ..");
		if(!BankAuditUtil.isEmptyString(pwd)
				 && !BankAuditUtil.isEmptyString(userId) && legalEntityCode !=null) {
			try {
				logger.info("Inside .. ..");
				String updateStatus = userService.updateUserPassword(legalEntityCode, userId, pwd);
				if("SUCCESS".equalsIgnoreCase(updateStatus)) {
					serviceStatus.setStatus("success");
					serviceStatus.setMessage("successsfully Inserted ");
				}else {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("No records to Insert ");
				}
			} catch (Exception e) {
				e.printStackTrace();
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("failure");
			}
		}else {
			serviceStatus.setStatus("failure");
			serviceStatus.setMessage("payload  not valid");
		}
		
		return serviceStatus; 
	}*/
	
	//Test service for cors issue
	
	
@RequestMapping(value = "/preflight", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus getPreflightRequest() {
		ServiceStatus serviceStatus = new ServiceStatus();
		serviceStatus.setStatus("success");
		serviceStatus.setMessage("successsfully requested");
		return serviceStatus;
	}
	
	// Service to delete the Records, 
		
@RequestMapping(value="/deleteUserByID/{legalEntityCode}/{userId}/{makerId}",method=RequestMethod.DELETE,produces=MediaType.APPLICATION_JSON_VALUE)
		ServiceStatus deleteUserByID(@PathVariable("legalEntityCode")Integer legalEntityCode,
				@PathVariable("userId") String userId,@PathVariable("makerId") String makerId){
		ServiceStatus serviceStatus=new ServiceStatus();
			
			if(legalEntityCode !=null && !BankAuditUtil.isEmptyString(userId) && !BankAuditUtil.isEmptyString(makerId)){
				try {
					userService.deleteUserByID(legalEntityCode, userId, makerId);
					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="/getReportingUsers",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE) 
		ServiceStatus getReportingUsers(
				@RequestParam("legalEntityCode")String legalEntityCodeStr,
				@RequestParam(required=false,value="unitCode") String unitCode,
				@RequestParam(required=false,value="userId") String userId,
				@RequestParam(required=false,value="typeOfUser") String typeOfUser
				){
			ServiceStatus serviceStatus=new ServiceStatus();
						
			if(!BankAuditUtil.isEmptyString(legalEntityCodeStr)){
				try {
					Integer legalEntityCode=Integer.parseInt(legalEntityCodeStr);
					List<User> users = userService.getReportingUsers(legalEntityCode,unitCode,userId,typeOfUser);
					if(users!=null && !users.isEmpty()){
						serviceStatus.setStatus("success");
						serviceStatus.setMessage("successfuly retrieved");
						serviceStatus.setResult(users);
					} else {
						serviceStatus.setStatus("failure");
						serviceStatus.setMessage("no records found");
					}						
				} catch (Exception e) {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("failure");
					e.printStackTrace();
				}			
			}else {
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("legalEntityCode required");
			}
			return serviceStatus;
		}
		
		
@RequestMapping(value="/getReportingUsersFromParent",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE) 
		ServiceStatus getReportingUsersFromParent(
				@RequestParam("legalEntityCode")String legalEntityCodeStr,
				@RequestParam(required=false,value="unitCode") String unitCode,
				@RequestParam(required=false,value="userId") String userId,
				@RequestParam(required=false,value="typeOfUser") String typeOfUser
				){
			ServiceStatus serviceStatus=new ServiceStatus();
						
			if(!BankAuditUtil.isEmptyString(legalEntityCodeStr)){
				try {
					Integer legalEntityCode=Integer.parseInt(legalEntityCodeStr);
					List<User> users = userService.getReportingUsersFromParent(legalEntityCode,unitCode,userId,typeOfUser);
					if(users!=null && !users.isEmpty()){
						serviceStatus.setStatus("success");
						serviceStatus.setMessage("successfuly retrieved");
						serviceStatus.setResult(users);
					} else {
						serviceStatus.setStatus("failure");
						serviceStatus.setMessage("no records found");
					}						
				} catch (Exception e) {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("failure");
					e.printStackTrace();
				}			
			}else {
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("legalEntityCode required");
			}
			return serviceStatus;
		}
		
		
@RequestMapping(value="/getImmedieateReportingUsers",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE) 
		ServiceStatus getImmedieateReportingUsers(
				@RequestParam("legalEntityCode")String legalEntityCodeStr,
				@RequestParam(required=false,value="unitCode") String unitCode,
				@RequestParam(required=false,value="userId") String userId,
				@RequestParam(required=false,value="typeOfUser") String typeOfUser,
				@RequestParam(required=false,value="onlyParent") Boolean onlyParent, // Yes means only Parent, from all the Units above current unit
				@RequestParam(required=false,value="inclusionHO") Boolean inclusionHO
				){
			ServiceStatus serviceStatus=new ServiceStatus();
						
			if(!BankAuditUtil.isEmptyString(legalEntityCodeStr) && (!BankAuditUtil.isEmptyString(unitCode) || !BankAuditUtil.isEmptyString(userId))){
				try {
					Integer legalEntityCode=Integer.parseInt(legalEntityCodeStr);
					List<User> users = userService.getImmedieateReportingUsers(legalEntityCode,unitCode,userId,typeOfUser, onlyParent, inclusionHO);
					if(users!=null && !users.isEmpty()){
						serviceStatus.setStatus("success");
						serviceStatus.setMessage("successfuly retrieved");
						serviceStatus.setResult(users);
					} else {
						serviceStatus.setStatus("failure");
						serviceStatus.setMessage("no records found");
					}						
				} catch (Exception e) {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("failure");
					e.printStackTrace();
				}			
			}else {
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("legalEntityCode required");
			}
			return serviceStatus;
		}
		
		
@RequestMapping(value="/getReportReviewer",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE) 
		ServiceStatus getReportReviewer(
				@RequestParam("legalEntityCode")String legalEntityCodeStr,
				@RequestParam("unitCode") String unitCode,
				@RequestParam(required=false,value="onlyParent") Boolean onlyParent, // Yes means only Parent, from all the Units above current unit
				@RequestParam(required=false,value="inclusionHO") Boolean inclusionHO
				){
			ServiceStatus serviceStatus=new ServiceStatus();
						
			if(!BankAuditUtil.isEmptyString(legalEntityCodeStr) && !BankAuditUtil.isEmptyString(unitCode) ){
				try {
					Integer legalEntityCode=Integer.parseInt(legalEntityCodeStr);
					List<User> users = userService.getReportReviewer(legalEntityCode,unitCode, onlyParent, inclusionHO);
					if(users!=null && !users.isEmpty()){
						serviceStatus.setStatus("success");
						serviceStatus.setMessage("successfuly retrieved");
						serviceStatus.setResult(users);
					} else {
						serviceStatus.setStatus("failure");
						serviceStatus.setMessage("no records found");
					}						
				} catch (Exception e) {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("failure");
					e.printStackTrace();
				}			
			}else {
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("legalEntityCode required");
			}
			return serviceStatus;
		}
		
		
@RequestMapping(value="/getReportReviewerRO",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE) 
		ServiceStatus getReportReviewerRO(
				@RequestParam("legalEntityCode")String legalEntityCodeStr,
				@RequestParam("unitCode") String unitCode,
				@RequestParam(required=false,value="onlyParent") Boolean onlyParent, // Yes means only Parent, from all the Units above current unit
				@RequestParam(required=false,value="inclusionHO") Boolean inclusionHO
				){
			ServiceStatus serviceStatus=new ServiceStatus();
						
			if(!BankAuditUtil.isEmptyString(legalEntityCodeStr) && !BankAuditUtil.isEmptyString(unitCode) ){
				try {
					Integer legalEntityCode=Integer.parseInt(legalEntityCodeStr);
					List<User> users = userService.getReportReviewerRO(legalEntityCode,unitCode, onlyParent, inclusionHO);
					if(users!=null && !users.isEmpty()){
						serviceStatus.setStatus("success");
						serviceStatus.setMessage("successfuly retrieved");
						serviceStatus.setResult(users);
					} else {
						serviceStatus.setStatus("failure");
						serviceStatus.setMessage("no records found");
					}						
				} catch (Exception e) {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("failure");
					e.printStackTrace();
				}			
			}else {
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("legalEntityCode required");
			}
			return serviceStatus;
		}
		
		
@RequestMapping(value="/getReviewerHO",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE) 
		ServiceStatus getReviewerHO(
				@RequestParam("legalEntityCode")String legalEntityCodeStr,
				@RequestParam("unitCode") String unitCode){
			ServiceStatus serviceStatus=new ServiceStatus();
						
			if(!BankAuditUtil.isEmptyString(legalEntityCodeStr) && !BankAuditUtil.isEmptyString(unitCode) ){
				try {
					Integer legalEntityCode=Integer.parseInt(legalEntityCodeStr);
					List<User> users = userService.getReviewerHO(legalEntityCode,unitCode);
					if(users!=null && !users.isEmpty()){
						serviceStatus.setStatus("success");
						serviceStatus.setMessage("successfuly retrieved");
						serviceStatus.setResult(users);
					} else {
						serviceStatus.setStatus("failure");
						serviceStatus.setMessage("no records found");
					}						
				} catch (Exception e) {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("failure");
					e.printStackTrace();
				}			
			}else {
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("legalEntityCode required");
			}
			return serviceStatus;
		}
		
		
@RequestMapping(value="/getReportReviewerApprover",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE) 
		ServiceStatus getReportReviewerApprover(
				@RequestParam("legalEntityCode")String legalEntityCodeStr,
				@RequestParam("unitCode") String unitCode,
				@RequestParam(required=false,value="onlyRO") Boolean onlyRO, 
				@RequestParam(required=false,value="onlyHO") Boolean onlyHO
				){
			ServiceStatus serviceStatus=new ServiceStatus();
						
			if(!BankAuditUtil.isEmptyString(legalEntityCodeStr) && !BankAuditUtil.isEmptyString(unitCode) ){
				try {
					Integer legalEntityCode=Integer.parseInt(legalEntityCodeStr);
					List<User> users = userService.getReportReviewerApprover(legalEntityCode,unitCode, onlyRO, onlyHO);
					if(users!=null && !users.isEmpty()){
						serviceStatus.setStatus("success");
						serviceStatus.setMessage("successfuly retrieved");
						serviceStatus.setResult(users);
					} else {
						serviceStatus.setStatus("failure");
						serviceStatus.setMessage("no records found");
					}						
				} catch (Exception e) {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("failure");
					e.printStackTrace();
				}			
			}else {
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("legalEntityCode required");
			}
			return serviceStatus;
		}
		
		
@RequestMapping(value="/getAuditorsByAuditId",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE) 
		ServiceStatus getAuditorsByAuditId(
				@RequestParam("legalEntityCode")String legalEntityCodeStr,
				@RequestParam("auditId") String auditId){
			ServiceStatus serviceStatus=new ServiceStatus();
						
			if(!BankAuditUtil.isEmptyString(legalEntityCodeStr) && !BankAuditUtil.isEmptyString(auditId) ){
				try {
					Integer legalEntityCode=Integer.parseInt(legalEntityCodeStr);
					List<User> users = userService.getAuditorsByAuditId(legalEntityCode, auditId);
					if(users!=null && !users.isEmpty()){
						serviceStatus.setStatus("success");
						serviceStatus.setMessage("successfuly retrieved");
						serviceStatus.setResult(users);
					} else {
						serviceStatus.setStatus("failure");
						serviceStatus.setMessage("no records found");
					}						
				} catch (Exception e) {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("failure");
					e.printStackTrace();
				}			
			}else {
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("legalEntityCode required");
			}
			return serviceStatus;
		}
		
		
@RequestMapping(value="/getReportReviewerROAndAuditors",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE) 
		ServiceStatus getReportReviewerROAndAuditors(
				@RequestParam("legalEntityCode")String legalEntityCodeStr,
				@RequestParam("unitCode") String unitCode,
				@RequestParam("auditId") String auditId,
				@RequestParam(required=false,value="onlyParent") Boolean onlyParent, // Yes means only Parent, from all the Units above current unit
				@RequestParam(required=false,value="inclusionHO") Boolean inclusionHO,
				@RequestParam(required=false,value="userType") String userType
				){
			ServiceStatus serviceStatus=new ServiceStatus();
						
			if(!BankAuditUtil.isEmptyString(legalEntityCodeStr) && !BankAuditUtil.isEmptyString(unitCode) ){
				try {
					Integer legalEntityCode=Integer.parseInt(legalEntityCodeStr);
					List<User> users = userService.getReportReviewerROAndAuditors(legalEntityCode,unitCode, auditId, onlyParent, inclusionHO, userType);
					if(users!=null && !users.isEmpty()){
						serviceStatus.setStatus("success");
						serviceStatus.setMessage("successfuly retrieved");
						serviceStatus.setResult(users);
					} else {
						serviceStatus.setStatus("failure");
						serviceStatus.setMessage("no records found");
					}						
				} catch (Exception e) {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("failure");
					e.printStackTrace();
				}			
			}else {
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("legalEntityCode required");
			}
			return serviceStatus;
		}
		
		
@RequestMapping(value="/isUserBelongsToSameUnitHierarchy",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE) 
		ServiceStatus isUserBelongsToSameUnitHierarchy(
				@RequestParam("legalEntityCode")String legalEntityCodeStr,
				@RequestParam("unitCode") String unitCode,
				@RequestParam("userCode") String userId,
				@RequestParam(required=false,value="userUnitCode") String userUnitCode
				){
			ServiceStatus serviceStatus=new ServiceStatus();
						
			if(!BankAuditUtil.isEmptyString(legalEntityCodeStr)){
				try {
					Integer legalEntityCode=Integer.parseInt(legalEntityCodeStr);
					boolean isUserBelongs = userService.isUserBelongsToSameUnitHierarchy(legalEntityCode,unitCode,userId,userUnitCode);
					if(isUserBelongs){
						serviceStatus.setStatus("success");
						serviceStatus.setMessage("User belongs to the same unit of hierarchy");
						serviceStatus.setResult(isUserBelongs);
					} else {
						serviceStatus.setStatus("success");
						serviceStatus.setMessage("User doesn't belongs to the same unit of hierarchy");
					}						
				} catch (Exception e) {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("failure");
					e.printStackTrace();
				}			
			}else {
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("legalEntityCode required");
			}
			return serviceStatus;
		}
		
		
@RequestMapping(value="/getFYEOUser",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE) 
		ServiceStatus getFYEOUser(
				@RequestParam("legalEntityCode")String legalEntityCodeStr,
				@RequestParam("unitCode") String unitCode,
				@RequestParam(required=false,value="onlyParent") Boolean onlyParent, // Yes means only Parent, from all the Units above current unit
				@RequestParam(required=false,value="inclusionHO") Boolean inclusionHO
				){
			ServiceStatus serviceStatus=new ServiceStatus();
						
			if(!BankAuditUtil.isEmptyString(legalEntityCodeStr) && !BankAuditUtil.isEmptyString(unitCode) ){
				try {
					Integer legalEntityCode=Integer.parseInt(legalEntityCodeStr);
					List<User> users = userService.getFYEOUser(legalEntityCode,unitCode, onlyParent, inclusionHO);
					if(users!=null && !users.isEmpty()){
						serviceStatus.setStatus("success");
						serviceStatus.setMessage("successfuly retrieved");
						serviceStatus.setResult(users);
					} else {
						serviceStatus.setStatus("failure");
						serviceStatus.setMessage("no records found");
					}						
				} catch (Exception e) {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("failure");
					e.printStackTrace();
				}			
			}else {
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("legalEntityCode required");
			}
			return serviceStatus;
		}
		
		
@RequestMapping(value="/getUnitLevelforUser/{legalEntityCode}/{userId}",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE)
		ServiceStatus getUnitLevelforUser(@PathVariable("legalEntityCode")Integer legalEntityCode,	@PathVariable("userId") String userId){
			ServiceStatus serviceStatus=new ServiceStatus();
			if(legalEntityCode!=null && !BankAuditUtil.isEmptyString(userId) ){
				try {
				    String userLevel=userService.getUnitLevelforUser(legalEntityCode,userId);
			    	serviceStatus.setResult(userLevel);
				    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="/validateToken",method=RequestMethod.POST,consumes=MediaType.APPLICATION_JSON_VALUE,produces=MediaType.APPLICATION_JSON_VALUE)
		ServiceStatus validateToken(@RequestBody ChangePasswordDto changePasswordDto){
			
			ServiceStatus serviceStatus=new ServiceStatus();
			if(changePasswordDto!=null
					&& changePasswordDto.getUserId()!=null
					&& changePasswordDto.getLegalEntityCode()!=null
					&& changePasswordDto.getToken()!=null){
				try {
					String validateToken=userResetPasswordService.validateLink(changePasswordDto);
					logger.info("inside resetPassword validate .."+validateToken);
					if(validateToken.equals("valid")) {
						serviceStatus.setStatus("success");
						serviceStatus.setMessage("successfully updated");	
					}else {
						serviceStatus.setStatus("failure");
						serviceStatus.setMessage(validateToken);	
					}
				} 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 user payload");
			}		
			return serviceStatus;
		}
		
			 
		
@RequestMapping(method = RequestMethod.DELETE, value = "/logout")		     
	    public void revokeToken(HttpServletRequest request,
	    		@RequestHeader(name = "Authorization", required = true) String authorization) {
	       // String authorization = request.getHeader("Authorization");
	        // if (authorization != null && authorization.contains("Bearer")){
	        //     String tokenId = authorization.substring("Bearer".length()+1);
	        //     tokenServices.revokeToken(tokenId);
	        // }
	    }
		
		
@RequestMapping(value="/testCall",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE) 
		public String testCall(){
			ServiceStatus serviceStatus=new ServiceStatus();
						
						return "BaasDosLcl->TestCall";
		}
	
}
