package org.academiadecodigo.enuminatti.cadetregistry.services;

import org.academiadecodigo.enuminatti.cadetregistry.models.User;

import java.util.LinkedList;
import java.util.List;

/**
 * MIT License
 * (c) 2017 Ricardo Constantino
 */

public class MockUserService implements UserService {

    private List<User> userList;
    private String errorStatus;

    public MockUserService() {
        this.userList = new LinkedList<>();
    }

    @Override
    public boolean authenticate(String user, String password) {
        User queriedUser = findByName(user);
        if (queriedUser == null) {
            setErrorStatus("No such user.");
            return false;
        }
        if (!queriedUser.getPassword().equals(password)) {
            setErrorStatus("Wrong password.");
            return false;
        }
        setErrorStatus("Logged in successfully.");
        return true;
    }

    @Override
    public void addUser(User newUser) {
        userList.add(newUser);
        setErrorStatus("Registered new user '" + newUser.getUsername() + "'");
    }

    @Override
    public User findByName(String username) {
        for (User user : userList) {
            if (user.getUsername().equals(username)) {
                return user;
            }
        }
        setErrorStatus("Couldn't find user.");
        return null;
    }

    @Override
    public int count() {
        return userList.size();
    }

    @Override
    public String getErrorStatus() {
        return errorStatus;
    }

    private void setErrorStatus(String errorStatus) {
        this.errorStatus = errorStatus;
    }
}
