/*******************************************************************************
 * Copyright 2Fi Business Solutions Ltd.
 *
 * This code is copyrighted. Under no circumstances should any party, people,
 * or organization should redistribute any portions of this code in any form,
 * either verbatim or through electronic media, to any third parties, unless
 * under explicit written permission by 2Fi Business Solutions Ltd.
 ******************************************************************************/
package com.ffii.core.security.service;

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

import com.ffii.core.dao.JdbcDao;
import com.ffii.core.utils.MapUtils;
import com.ffii.core.web.AbstractService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

/**
 * Login Log Service
 *
 * @author Patrick
 */
@Service
public class LoginLogService extends AbstractService {

	@Autowired
	private JdbcDao jdbcDao;

	/**
	 * Create Login Log record
	 *
	 * @param username
	 *            the username
	 * @param remoteAddr
	 *            request.getRemoteAddr()
	 * @param success
	 *            true if the login is successful, else false
	 *
	 * @return true if the number of rows inserted is 1
	 */
	@Transactional(isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class, readOnly = false)
	public boolean createLoginLog(String username, String remoteAddr, boolean 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.executeInsert("user_login_log", 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));
	}

}
