package org.academiadecodigo.enuminatti.restuser.services;

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

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

public class MockUserService implements UserService {
    private Map<Integer, User> users;
    private int lastId;

    public MockUserService() {
        this.users = new HashMap<>();
        this.lastId = 0;
    }

    public MockUserService(Map<Integer, User> users) {
        this.users = users;
        Integer[] usersIdArray = users.keySet().toArray(new Integer[0]);
        this.lastId = usersIdArray.length > 0 ? usersIdArray[usersIdArray.length-1] : 0;
    }

    @Override
    public void add(User user) {
        if (user == null) {
            return;
        }

        if (user.getId() == null) {
            user.setId(lastId++);
        }

        users.put(user.getId(), user);

    }

    @Override
    public void remove(int id) {
        users.remove(id);
    }

    @Override
    public User findById(int id) {
        return users.get(id);
    }

    @Override
    public User findByName(String name) {
        User foundUser = null;
        for (User user : users.values()) {
            if (name.equals(user.getName())) {
                foundUser = user;
            }
        }
        return foundUser;
    }

    @Override
    public List<User> findAll() {
        return new ArrayList<>(users.values());
    }
}
