package com.purui.prims.auth.authentication.service;

import com.purui.prims.auth.api.authentication.pojo.User;
import com.purui.prims.auth.api.authentication.request.UserReq;
import com.purui.prims.auth.api.authentication.response.RoleResp;
import com.purui.prims.auth.api.authentication.service.UserService;
import com.purui.prims.auth.api.authentication.utils.UserHolder;
import com.purui.prims.auth.authentication.utils.ComponentFactory;
import com.purui.prims.common.config.SystemConfig;
import com.purui.prims.common.service.SystemConfigService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Set;

@Service
public class UserServiceImpl implements UserService {

    private SystemConfigService sysParameterService;

    public UserServiceImpl(SystemConfigService sysParameterService) {
        this.sysParameterService = sysParameterService;
    }

    @Override
    public User getCurrentUser(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
        User user = UserHolder.findUser(httpServletRequest, httpServletResponse);
        if (user != null) {
            SystemConfig systemConfig = sysParameterService.getSystemConfig();
            if (!CollectionUtils.isEmpty(systemConfig.getAdmins())
                    && systemConfig.getAdmins().contains(user.getUserName())) {
                user.setIsAdmin(1);
            }
        }
        return user;
    }

    @Override
    public List<String> getUserNames() {
        return ComponentFactory.getUserAdaptor().getUserNames();
    }

    @Override
    public List<User> getUserList() {
        return ComponentFactory.getUserAdaptor().getUserList();
    }

    @Override
    public Set<String> getUserAllOrgId(String userName) {
        return ComponentFactory.getUserAdaptor().getUserAllOrgId(userName);
    }

    @Override
    public List<User> getUserByOrg(String key) {
        return ComponentFactory.getUserAdaptor().getUserByOrg(key);
    }

    @Override
    public List<RoleResp> getRoles() {
        return ComponentFactory.getUserAdaptor().getRoles();
    }

    @Override
    public void register(UserReq userReq) {
        ComponentFactory.getUserAdaptor().register(userReq);
    }

    @Override
    public void update(UserReq userCmd) {
        ComponentFactory.getUserAdaptor().update(userCmd);
    }

    @Override
    public String login(UserReq userReq, HttpServletRequest request) {
        return ComponentFactory.getUserAdaptor().login(userReq, request);
    }

    @Override
    public String login(UserReq userReq, String appKey) {
        return ComponentFactory.getUserAdaptor().login(userReq, appKey);
    }

}
