package backend.service;
import backend.dao.UserDao;
import backend.model.enums.LoginStatus;
import backend.model.User;

import java.util.List;
import java.util.Vector;

public class AuthService {
    private UserDao userDao = new UserDao();

    public boolean addUser(User user) {
        return userDao.addUser(user);
    }

    public boolean deleteUser(int id) {
        return userDao.deleteUser(id);
    }

    public LoginStatus login(User user) {
        User dbUser = userDao.findByUsername(user.getUsername());
        if(dbUser==null)
            return LoginStatus.USER_NOT_FOUND;
        if(dbUser.getUsername().equals(user.getUsername())&&dbUser.getPassword().equals(user.getPassword()))
            return LoginStatus.SUCCESS;
        else if (!dbUser.getUsername().equals(user.getUsername())) {
            return LoginStatus.USER_NOT_FOUND;
        }
        return LoginStatus.PASSWORD_ERROR;
    }

    public LoginStatus register(User user) {
        User dbAccount = userDao.findByUsername(user.getUsername());
        if(dbAccount!=null)
            return LoginStatus.REGISTER_FAILED;
        //点击注册按钮后的事件
        if(userDao.addUser(user))
            return LoginStatus.REGISTER_SUCCESS;
        else
            return LoginStatus.REGISTER_FAILED;
    }

    public boolean updateUser(User user) {
        return userDao.updateUser(user);
    }

    private Vector<Vector<String>> commonHandler(List<User> usersList){
        //加工数据 把数据库查到的List转成Vector<Vector<>>
        Vector<Vector<String>> usersData = new Vector<>();
        if(usersList != null) {
            for (User usersPo : usersList) {
                Vector<String> row = new Vector<>();
                row.add(String.valueOf(usersPo.getId()));
                row.add(usersPo.getUsername());
                row.add(usersPo.getRole());
                row.add(usersPo.getEmail());
                row.add(String.valueOf(usersPo.getCreatedAt()));
                usersData.add(row);
            }
        }
        return usersData;
    }

    public Vector<Vector<String>> getAll(){
        //从数据库中获取所有用户
        List<User> usersList = userDao.findAll();
        //把List转成表格所需的格式
        return commonHandler(usersList);
        //返回给前端
    }
    public Vector<Vector<String>> getByCondition(String role, String key){
        //从数据库中获取所有用户
        List<User> usersList = userDao.findByCondition(role,key);
        //把List转成表格所需的格式
        return commonHandler(usersList);
        //返回给前端
    }
    public static void main(String[] args) {
        UserDao userDao = new UserDao();
        AuthService authService = new AuthService();
        Vector<Vector<String>> users= authService.commonHandler(userDao.findAll());
        System.out.println(users);
    }
}

