package chapter4.demo49;

import java.util.HashMap;
import java.util.Map;

class UserManager {
    // 保证单例模式
    private static UserManager instance;
    // 存储所有用户
    private Map<String, AbstractUser> users;

    private UserManager() {
        users = new HashMap<>();
        // 初始化一个管理员账号
        users.put("admin", new AdminUser("admin", "admin123"));
    }

    // 单例模式
    public static UserManager getInstance() {
        if (instance == null) {
            instance = new UserManager();
        }
        return instance;
    }

    public void addUser(AbstractUser user) throws UserException {
        if (users.containsKey(user.getUsername())) {
            throw new UserException("用户名已存在！");
        }
        users.put(user.getUsername(), user);
    }

    public AbstractUser login(String username, String password) throws UserException {
        AbstractUser user = users.get(username);
        if (user == null) {
            throw new UserException("用户不存在！");
        }
        if (!user.checkPassword(password)) {
            throw new UserException("用户名或密码错误！");
        }
        return user;
    }

    public void removeUser(String username) {
        users.remove(username);
    }

    public void showAllUsers() {
        System.out.println("当前系统用户列表：");
        for (AbstractUser user : users.values()) {
            user.showInfo();
        }
    }
}
