package com.uca.core;

import com.uca.dao.PokemonDAO;
import com.uca.dao.UserDAO;
import com.uca.entity.UserEntity;
import com.uca.exceptions.ServiceException;
import org.h2.engine.User;
import org.mindrot.jbcrypt.BCrypt;

import java.time.LocalDate;
import java.util.ArrayList;

public class UserCore {

    private static final UserDAO userDAO = new UserDAO();

    public static ArrayList<UserEntity> getAll() throws ServiceException {
        return userDAO.getAll();
    }

    public static UserEntity getByIdentifier(String identifier, boolean keepPassword) throws ServiceException {
        UserEntity entity = userDAO.getByIdentifier(identifier);

        if (entity.getId() == 0) {
            throw new ServiceException("This user does not exist");
        }

        if (!keepPassword) {
            entity.setPassword(null);
        }

        return entity;
    }

    public static UserEntity getById(int id) throws ServiceException {
        UserEntity entity = userDAO.getById(id);

        if (entity.getId() == 0) {
            throw new ServiceException("This user does not exist");
        }

        return entity;
    }

    public static UserEntity create(String firstname, String lastname, String identifier, String password) throws ServiceException {
        try {
            getByIdentifier(identifier, false);
        } catch (ServiceException e) {
            UserEntity entity = new UserEntity();
            entity.setFirstName(firstname);
            entity.setLastName(lastname);
            entity.setIdentifier(identifier);
            entity.setPassword(BCrypt.hashpw(password, BCrypt.gensalt()));
            entity.setLastConnection(LocalDate.of(1970,1,1));
            entity.resetNbUpgrades();
            return userDAO.create(entity);
        }

        throw new ServiceException("A user already exists with this identifier.");
    }

    public static void update(int id, String firstname, String lastname, String identifier) throws ServiceException {
        UserEntity entity = new UserEntity();
        entity.setFirstName(firstname);
        entity.setLastName(lastname);
        entity.setIdentifier(identifier);
        userDAO.update(id, entity);
    }

    public static void updateLastConnection(UserEntity user) throws ServiceException {
        user.setLastConnection(LocalDate.now());
        userDAO.update(user.getId(), user);
    }

    public static void resetNbUpgrades(UserEntity user) throws ServiceException {
        user.resetNbUpgrades();
        userDAO.update(user.getId(), user);
    }

    public static void useOneUpgrade(UserEntity user) throws ServiceException {
        user.useOneUpgrade();
        userDAO.update(user.getId(), user);
    }

    public static void updatePassword(UserEntity user, String password) throws ServiceException {
        userDAO.updatePassword(user.getId(), password);
    }

    public static void delete(int id) throws ServiceException {
        userDAO.delete(id);
    }
}
