/*
 * 
 */
package com.bankaudit.service;



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

import org.jboss.logging.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailMessage;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.bankaudit.dao.UserResetPasswordDao;
import com.bankaudit.dto.ChangePasswordDto;
import com.bankaudit.model.UserResetPassword;
import com.bankaudit.model.UserResetPasswordHst;
import com.bankaudit.spring.config.EmailConfig;
import com.bankaudit.util.RandomStringUtil;

/**
 * {@link UserResetPasswordServiceImpl} class implements the methods of {@link UserService}
 * interface.
 *
 * @author amit.patel 
 * @version 1.0
 */
@Service("userResetPasswordService")
@Transactional("transactionManager")
public class UserResetPasswordServiceImpl implements UserResetPasswordService {

	
	/** The User Reset Password DAO is autowired and make methods available from dao layer . */
	@Autowired
	UserResetPasswordDao userResetPasswordDao;
	
	@Autowired
	BusinessDateService businessDateService;
	
	
	@Autowired
	EmailConfig emailConfig;
	
	
	static final Logger logger = Logger.getLogger(UserResetPasswordServiceImpl.class);
	
	@Override
	public UserResetPassword createUserResetPassword(Integer legalEntityCode,String userId)throws Exception {
		UserResetPassword userResetPassword = null;
		UserResetPassword alreadyExistingUserResetPassword = null;
		Map<String,Object> properties= null;
		
		try {

			// if already exist
			properties=new HashMap<String, Object >();
			properties.put("legalEntityCode",legalEntityCode);
			properties.put("userId",userId);
			
			alreadyExistingUserResetPassword=(UserResetPassword)userResetPasswordDao.getUniqueEntityByMatchingProperties(UserResetPassword.class, properties);
			
			logger.info("Already Existing UserResetPassword :"+alreadyExistingUserResetPassword);
			
			
			if(alreadyExistingUserResetPassword!=null){
				UserResetPasswordHst userResetPasswordHst=new UserResetPasswordHst(); 
				BeanUtils.copyProperties(alreadyExistingUserResetPassword, userResetPasswordHst);
				userResetPasswordDao.save(userResetPasswordHst);				
				userResetPasswordDao.delete(alreadyExistingUserResetPassword);
				userResetPasswordDao.flushSession();		
			}
			
			int expiryTime = 120; // Default value 120 Mins
			try {
				expiryTime=userResetPasswordDao.getPwdExpiryTime(legalEntityCode);
			}catch(Exception e) {expiryTime =120;}
			logger.info("expiryTime .."+ expiryTime);
			userResetPassword=new UserResetPassword();
			userResetPassword.setLegalEntityCode(legalEntityCode);
			userResetPassword.setUserId(userId);
			userResetPassword.setInTime(new Timestamp(System.currentTimeMillis()));
			userResetPassword.setExpiryTime(expiryTime);
			userResetPassword.setToken(new RandomStringUtil(6).nextString());
			userResetPassword.setBusinessdateTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(legalEntityCode));
			userResetPassword.setSysdateTimestampRequest(new Timestamp(System.currentTimeMillis()));
			
			logger.info("New UserResetPassword :"+userResetPassword);
			
			userResetPasswordDao.save(userResetPassword);
			userResetPasswordDao.flushSession();
		}catch (Exception e) {
			logger.error(e.getMessage(),e);
			throw e;
		}
		return userResetPassword;
	}

	@Override
	public void sendEmail(String emailId,String token) {
		
		String body="Dear User," + "\n" + "Please use below Token Number to Change Password " ;
		body+="\n";
		body+="Token : "+token;
		body+="\n";
		body+="\n";
		body+=" This is a system-generated e-mail regarding your BAAS Password Reset, please don't reply to this message.";
		
		MailSender mailSender= emailConfig.javaMailSender();
        SimpleMailMessage message = new SimpleMailMessage();
		message.setTo(emailId);
        message.setSubject("Bank Audit:Token for Reset Password");
        message.setText(body);
        mailSender.send(message);
	}
	
	@Override
	public String validateLink(ChangePasswordDto changePasswordDto) {
		String validateLink=null;
		try {
			validateLink=userResetPasswordDao.validateLink(changePasswordDto);
			logger.info("serviceImpl validateLink .."+validateLink);
		}catch(Exception e) {
			
		}
		return validateLink;
	}
	
	@Override
	public String  getEmailIdforResetPassword(Integer legalEntityCode,String userId) {
		String emailId=null;
		try {
			emailId=userResetPasswordDao.getEmailIdforResetPassword(legalEntityCode,userId);
			logger.info("serviceImpl getEmailIdforResetPassword .."+emailId);
		}catch(Exception e) {
			
		}
		return emailId;
	}
	
	@Override
	public void resetPassword(ChangePasswordDto changePasswordDto) {
		UserResetPassword userResetPassword = null;
		UserResetPassword getUserRestDetailsMst = null;
		Map<String,Object> properties= null;
		try {
			userResetPasswordDao.resetPassword(changePasswordDto); // Reseting the password
			
			//To move the record from Mst to Hst and delete the Mst record
			properties=new HashMap<String, Object >();
			properties.put("legalEntityCode",changePasswordDto.getLegalEntityCode());
			properties.put("userId",changePasswordDto.getUserId());
			
			getUserRestDetailsMst=(UserResetPassword)userResetPasswordDao.getUniqueEntityByMatchingProperties(UserResetPassword.class, properties);
			logger.info("getUserRestDetailsMst :"+getUserRestDetailsMst);
						
			if(getUserRestDetailsMst!=null){
				UserResetPasswordHst userResetPasswordHst=new UserResetPasswordHst(); 
				BeanUtils.copyProperties(getUserRestDetailsMst, userResetPasswordHst);
				userResetPasswordHst.setSysdateTimestampActedOn(new Timestamp(System.currentTimeMillis())); // To capture the time when the Password Reset done
				userResetPasswordDao.save(userResetPasswordHst);				
				userResetPasswordDao.delete(getUserRestDetailsMst);
				userResetPasswordDao.flushSession();		
			}
		}catch(Exception e) {
			
		}
	}

}