package com.easyproject.core.web.service;

import java.util.concurrent.TimeUnit;

import com.easyproject.common.core.domain.entity.ClientMember;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import com.easyproject.common.constant.CacheConstants;
import com.easyproject.common.constant.Constants;
import com.easyproject.common.core.redis.RedisCache;
import com.easyproject.common.exception.user.UserPasswordNotMatchException;
import com.easyproject.common.exception.user.UserPasswordRetryLimitExceedException;
import com.easyproject.common.utils.MessageUtils;
import com.easyproject.common.utils.SecurityUtils;
import com.easyproject.core.manager.AsyncManager;
import com.easyproject.core.manager.factory.AsyncFactory;
import com.easyproject.core.security.context.AuthenticationContextHolder;

/**
 * 登录密码方法
 *
 * @author java001
 */
@Component
public class MemberPasswordService {
    @Autowired
    private RedisCache redisCache;

    //密码最大错误次数
    @Value(value = "${user.password.maxRetryCount}")
    private int maxRetryCount;

    //密码锁定时间（默认10分钟）
    @Value(value = "${user.password.lockTime}")
    private int lockTime;

    /**
     * 登录账户密码错误次数缓存键名
     *
     * @param username 用户名
     * @return 缓存键key
     */
    private String getCacheKey(String username) {
        return CacheConstants.CLIENT_PWD_ERR_CNT_KEY + username;
    }

    public void validate(ClientMember member) {
        Authentication usernamePasswordAuthenticationToken = AuthenticationContextHolder.getContext();
        String username = usernamePasswordAuthenticationToken.getName();
        String password = usernamePasswordAuthenticationToken.getCredentials().toString();

        Integer retryCount = redisCache.getCacheObject(getCacheKey(username));

        if (retryCount == null) {
            retryCount = 0;
        }

        if (retryCount >= Integer.valueOf(maxRetryCount).intValue()) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("member.login.retry.limit.exceed", maxRetryCount, lockTime)));
            throw new UserPasswordRetryLimitExceedException(maxRetryCount, lockTime);
        }

        if (!matches(member, password)) {
            retryCount = retryCount + 1;
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("member.login.retry.limit.count", retryCount)));
            redisCache.setCacheObject(getCacheKey(username), retryCount, lockTime, TimeUnit.MINUTES);
            throw new UserPasswordNotMatchException();
        } else {
            clearLoginRecordCache(username);
        }
    }

    public boolean matches(ClientMember member, String rawPassword) {
        return SecurityUtils.matchesPassword(rawPassword, member.getPassword());
    }

    public void clearLoginRecordCache(String loginName) {
        if (redisCache.hasKey(getCacheKey(loginName))) {
            redisCache.deleteObject(getCacheKey(loginName));
        }
    }
}
