package com.bankaudit.dao;

import java.sql.Timestamp;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.ScrollMode;
import org.hibernate.ScrollableResults;
import org.hibernate.Session;
import org.hibernate.transform.ResultTransformer;
import org.hibernate.transform.Transformers;
import org.jboss.logging.Logger;
import org.springframework.stereotype.Repository;

import com.bankaudit.constants.BankAuditConstant;
import com.bankaudit.dto.ChangePasswordDto;
import com.bankaudit.dto.DataTableResponse;
import com.bankaudit.model.User;
import com.bankaudit.model.UserWrk;
import com.bankaudit.rest.process.dao.MyAuditsDaoImpl;
import com.bankaudit.util.BankAuditUtil;

import java.util.ArrayList;

@Repository
public class UserResetPasswordDaoImpl extends AbstractDao implements UserResetPasswordDao {
	
	static final Logger logger = Logger.getLogger(UserResetPasswordDaoImpl.class);
			
	@SuppressWarnings("unchecked")
	@Override
	public void resetPassword(ChangePasswordDto changePasswordDto) {

		Session session=getSession();
		logger.info("UserResetPasswordDaoImp resetPassword().. "+changePasswordDto.getLegalEntityCode() + " userId.."+ changePasswordDto.getUserId());
		try {
			Date currentLogin=new Timestamp(System.currentTimeMillis());
			session.createQuery("update User u set "
					+ " u.password =:newPassword "
					+ " , u.currentLogin =:currentLogin "
					+ " where u.legalEntityCode =:legalEntityCode "
					+ " and u.userId =:userId" )
			.setParameter("legalEntityCode", changePasswordDto.getLegalEntityCode())
			.setParameter("userId", changePasswordDto.getUserId())
			.setParameter("newPassword", changePasswordDto.getNewPassword())
			.setParameter("currentLogin", currentLogin).executeUpdate();
		}catch(Exception e) {
			e.printStackTrace();
		}
		
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public String validateLink(ChangePasswordDto changePasswordDto) {

		Session session=getSession();
		String validateLink=null;
		try {
			logger.info("Inside validateLink :: "+ changePasswordDto.getToken() +" UserId:: "+changePasswordDto.getUserId());
			Date currentLogin=new Timestamp(System.currentTimeMillis());
			Query qry= session.createNativeQuery(" select "  
					+ " 	SUM(time_to_sec(TIMEDIFF(:currentLogin, in_time))) AS timesum, " 
					+ " 	token,expiry_time, legal_entity_code,user_id  "
					+ " FROM user_reset_password"
					+ " 	WHERE user_id=:userId"
					+ " 	AND legal_entity_code =:legalEntityCode ")
			.setParameter("legalEntityCode", changePasswordDto.getLegalEntityCode())
			.setParameter("userId", changePasswordDto.getUserId())
			.setParameter("currentLogin", currentLogin);
			
			Object obj = (Object)qry.getSingleResult();
			long timeDiff =0l;long expiryTime=0l;String token=null;
			if(obj !=null) {
				timeDiff = Long.parseLong(((Object[])obj)[0].toString());
				expiryTime = Long.parseLong(((Object[])obj)[2].toString());
				token = ((Object[])obj)[1].toString();
			}
			
			logger.info("timeDiff:: "+ timeDiff +" expiryTime:: "+expiryTime +" token:: "+token);
			if(changePasswordDto != null && !changePasswordDto.getToken().equals(token)) {
				validateLink ="Invalid token. Please try again with correct token.";
			}else if( timeDiff > expiryTime) {
				validateLink ="Token expired. Click on validate user to get the token again.";
			}else if(token != null){
				validateLink ="valid";
			}
			logger.info("validateLink .."+validateLink);
		}catch(Exception e) {
			e.printStackTrace();
		}return validateLink;
		
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public String getEmailIdforResetPassword(Integer legalEntityCode,String userId) {

		Session session=getSession();
		String emailId =null;
		logger.info("UserResetPasswordDaoImp getEmailIdforResetPassword().. "+ legalEntityCode + " userId.."+ userId);
		try {
			Date currentLogin=new Timestamp(System.currentTimeMillis());
			Object obj =session.createNativeQuery("SELECT email_id FROM user  "
					+ " WHERE legal_entity_code =:legalEntityCode "
					+ " AND user_id =:userId" )
			.setParameter("legalEntityCode", legalEntityCode)
			.setParameter("userId", userId).getSingleResult();
			if(obj != null) {
				if("".equalsIgnoreCase(obj.toString().trim())) emailId="NoEmail";
				else emailId = obj.toString().trim();
			}else {
				emailId = "InvalidUser";
			}			
			logger.info("emailId .."+emailId);
		}catch(Exception e) {
			//e.printStackTrace();
			if(e instanceof javax.persistence.NoResultException) {
				emailId = "InvalidUser";
			}
		} return emailId;
		
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public int getPwdExpiryTime(Integer legalEntityCode) {

		Session session=getSession();
		int pwdExpiryTime =120;
		logger.info("UserResetPasswordDaoImp getPwdExpiryTime().. "+ legalEntityCode );
		try {
			Date currentLogin=new Timestamp(System.currentTimeMillis());
			Object obj =session.createNativeQuery(" select * from general_parameter where "
					+ "legal_entity_code=:legalEntityCode and key_1 ='RESET_PWD_EXP_TIME' and key_2='RESET_PWD_EXP_TIME') ")
			.setParameter("legalEntityCode", legalEntityCode);
			if(obj != null) {
				pwdExpiryTime = Integer.parseInt(obj.toString());
			}		
			logger.info("pwdExpiryTime .."+pwdExpiryTime);
		}catch(Exception e) {
			//e.printStackTrace();
			if(e instanceof javax.persistence.NoResultException) {
				logger.info("There is no Parameter setup for the Expiry time of Reset Password ");
			}
		} return pwdExpiryTime;
		
	}
}
