package com.keao.edu.auth.service.impl;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.keao.edu.auth.api.entity.SysUser;
import com.keao.edu.auth.api.entity.SysUserLogin;
import com.keao.edu.auth.api.enums.UserLockFlag;
import com.keao.edu.auth.dal.dao.SysUserDao;
import com.keao.edu.auth.dal.dao.SysUserLoginDao;
import com.keao.edu.auth.service.SysUserLoginService;
import com.keao.edu.common.dal.BaseDAO;
import com.keao.edu.common.service.impl.BaseServiceImpl;

@Service
public class SysUserLoginServiceImpl extends BaseServiceImpl<Integer, SysUserLogin> implements SysUserLoginService {

	@Autowired
	private SysUserLoginDao sysUserLoginDao;

	@Autowired
	private SysUserDao sysUserDao;

	@Override
	public BaseDAO<Integer, SysUserLogin> getDAO() {
		return sysUserLoginDao;
	}

	@Override
	public SysUserLogin findLoginByUserId(Integer userId) {
		return sysUserLoginDao.findLoginByUserId(userId);
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public boolean autoUnlock() {
		List<SysUser> users = sysUserDao.queryByStatus(UserLockFlag.LOCKED);
		if (users != null) {
			SysUserLogin userLogin = null;
			Date targetDate = null;
			Date currentDate = new Date();
			Integer lockTime = null;
			for (SysUser user : users) {
				userLogin = get(user.getId());
				if (userLogin != null) {
					lockTime = userLogin.getLockTime();
					if (lockTime == null || lockTime == 0) {
						continue;
					}
					targetDate = DateUtils.addMinutes(userLogin.getLockDate(), lockTime);
					if (targetDate.getTime() < currentDate.getTime()) {
						userLogin.setFailCount(0);
						userLogin.setLockDate(null);
						userLogin.setLockTime(0);
						update(userLogin);

						user.setLockFlag(0);
						user.setUpdateTime(currentDate);
						sysUserDao.update(user);
					}
				}
			}
		}
		return false;
	}
}