package com.ffii.core.user.service;

import java.time.LocalDateTime;
import java.util.Map;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ffii.core.support.AbstractService;
import com.ffii.core.support.JdbcDao;

/** @author Fung */
@Service
public class UserAttemptService extends AbstractService {

	public UserAttemptService(JdbcDao jdbcDao) {
		super(jdbcDao);
	}

	public int findAttempt(String username) {
		return jdbcDao.queryForInt("SELECT attempt FROM user_attempt WHERE username = :username;",
				Map.of("username", username));
	}

	@Transactional(rollbackFor = Exception.class)
	public void loginSuccess(String username) {
		jdbcDao.executeUpdate(
				"INSERT INTO user_attempt (username,attempt,lastAttempted) VALUES (:username,0,:lastAttempted)"
						+ " ON DUPLICATE KEY UPDATE attempt = 0, lastAttempted = :lastAttempted;",
				Map.of("username", username, "lastAttempted", LocalDateTime.now()));
	}

	@Transactional(rollbackFor = Exception.class)
	public void loginFailure(String username) {
		jdbcDao.executeUpdate(
				"INSERT INTO user_attempt (username,attempt,lastAttempted) VALUES (:username,1,:lastAttempted)"
						+ " ON DUPLICATE KEY UPDATE attempt = attempt + 1, lastAttempted = :lastAttempted;",
				Map.of("username", username, "lastAttempted", LocalDateTime.now()));
	}

	@Transactional(rollbackFor = Exception.class)
	public void reset(String username) {
		loginSuccess(username);
	}
}
