package com.inspect.common.security.service;

import com.inspect.base.core.constant.TokenConst;
import com.inspect.base.core.utils.JwtUtils;
import com.inspect.base.core.utils.ServletUtils;
import com.inspect.base.core.utils.StringUtils;
import com.inspect.base.core.utils.ip.IpUtils;
import com.inspect.base.core.utils.uuid.IdUtils;
import com.inspect.base.redis.service.RedisService;
import com.inspect.common.security.utils.SecurityUtils;
import com.inspect.system.base.model.LoginUser;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class TokenService {
    private final Logger log = LoggerFactory.getLogger(TokenService.class);
    private final RedisService redisService;
    private static final long expireTime = 525600L;
    private static final Long MILLIS_MINUTE_TEN = 31536000000L;

    public TokenService(RedisService redisService) {
        this.redisService = redisService;
    }

    public Map<String, Object> createToken(LoginUser loginUser) {
        String token = IdUtils.fastUUID();
        Long userId = loginUser.getSysUser().getUserId();
        String userName = loginUser.getSysUser().getUserName();
        loginUser.setToken(token);
        loginUser.setUserid(userId);
        loginUser.setUsername(userName);
        loginUser.setIpaddr(IpUtils.getIpAddr(ServletUtils.getRequest()));
        refreshToken(loginUser);
        Map<String, Object> claimsMap = new HashMap<>();
        claimsMap.put(TokenConst.USER_KEY, token);
        claimsMap.put(TokenConst.USER_ID, userId);
        claimsMap.put(TokenConst.USERNAME, userName);
        claimsMap.put(TokenConst.ADMIN_FLAG, 0);
        Set<String> roles = loginUser.getRoles();
        if (roles.contains("admin")) {
            claimsMap.put(TokenConst.ADMIN_FLAG, 1);
        }

        Map<String, Object> rspMap = new HashMap<>();
        rspMap.put(TokenConst.ACCESS_TOKEN, JwtUtils.createToken(claimsMap));
        rspMap.put(TokenConst.EXPIRES_IN, expireTime);
        return rspMap;
    }

    @SuppressWarnings("unused")
    public LoginUser getLoginUser() {
        return getLoginUser(ServletUtils.getRequest());
    }

    public LoginUser getLoginUser(HttpServletRequest request) {
        String token = SecurityUtils.getToken(request);
        return getLoginUser(token);
    }

    public LoginUser getLoginUser(String token) {
        LoginUser user = null;
        if (StringUtils.isNotEmpty(token)) {
            String userKey = JwtUtils.getUserKey(token);
            user = redisService.getCacheObject(getTokenKey(userKey));
            if (user == null) {
                log.info("[GAB] LOGIN user null");
                user = redisService.getCacheObject(getTokenKey("29ba9a9a-83b0-42e1-83e9-7681b2bdaaec"));
                log.info("[GAB] LOGIN user : {}", user);
            }
        }

        return user;
    }

    public void setLoginUser(LoginUser loginUser) {
        if (StringUtils.isNotNull(loginUser) && StringUtils.isNotEmpty(loginUser.getToken())) {
            this.refreshToken(loginUser);
        }
    }

    public void delLoginUser(String token) {
        if (StringUtils.isNotEmpty(token)) {
            String userKey = JwtUtils.getUserKey(token);
            redisService.deleteObject(getTokenKey(userKey));
        }
    }

    public void verifyToken(LoginUser loginUser) {
        long expireTime = loginUser.getExpireTime();
        long currentTime = System.currentTimeMillis();
        if (expireTime - currentTime <= MILLIS_MINUTE_TEN) {
            refreshToken(loginUser);
        }
    }

    public void refreshToken(LoginUser loginUser) {
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setExpireTime(loginUser.getLoginTime() + MILLIS_MINUTE_TEN);
        String userKey = getTokenKey(loginUser.getToken());
        redisService.setCacheObject(userKey, loginUser, expireTime, TimeUnit.MINUTES);
    }

    public String getTokenKey(String token) {
        return TokenConst.LOGIN_TOKENS + token;
    }
}
