package com.ffii.fpsms.config.security.service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

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

@Service
public class LoginLogService extends AbstractService {

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

	@Transactional(isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class, readOnly = false)
	public boolean createLoginLog(String username, String remoteAddr, boolean success) {
		String sql = "INSERT INTO user_login_log (`username`, `loginTime`, `ipAddr`, `success`) "
			+"VALUES (:username, :loginTime, :ipAddr, :success)";
		Map<String, Object> args = new HashMap<>(4);
		args.put("username", username);
		args.put("loginTime", new Date());
		args.put("ipAddr", remoteAddr);
		args.put("success", success);

		return (jdbcDao.executeUpdate(sql, args) == 1);
	}

	@Transactional(isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class, readOnly = true)
	public List<Map<String, Object>> listLastLog(String username, int limit) {
		return jdbcDao.queryForList("SELECT success FROM user_login_log where username = :username ORDER BY loginTime DESC LIMIT " + limit,
				MapUtils.toHashMap("username", username));
	}

}
