package com.purui.prims.auth.api.authentication.utils;

import com.purui.prims.auth.api.authentication.pojo.User;
import com.purui.prims.auth.api.authentication.service.UserStrategy;
import com.purui.prims.common.config.SystemConfig;
import com.purui.prims.common.service.SystemConfigService;
import com.purui.prims.common.util.ContextUtils;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public final class UserHolder {

    private static UserStrategy REPO;

    public static synchronized void setStrategy(UserStrategy strategy) {
        REPO = strategy;
    }

    public static User findUser(HttpServletRequest request, HttpServletResponse response) {
        User user = REPO.findUser(request, response);
        return getUser(user);
    }

    public static User findUser(String token, String appKey) {
        User user = REPO.findUser(token, appKey);
        return getUser(user);
    }

    private static User getUser(User user) {
        SystemConfigService sysParameterService = ContextUtils.getBean(SystemConfigService.class);
        SystemConfig systemConfig = sysParameterService.getSystemConfig();
        if (!CollectionUtils.isEmpty(systemConfig.getAdmins())
                && systemConfig.getAdmins().contains(user.getUserName())) {
            user.setIsAdmin(1);
        }
        return user;
    }

}
