package fr.imta.addressbook.model;

import java.util.ArrayList;
import java.util.List;

public class Database {
    private List<AddressBook> addressBooks;
    private List<Person> persons;

    public Database() {
        this.addressBooks = new ArrayList<>();
        this.persons = new ArrayList<>();
        seed();
    }

    // this function create the initial content of the database
    private void seed() {
        Person donald = new Person("Donald", "Duck");
        Person riri = new Person("Riri", "Duck");
        Person fifi = new Person("Fifi", "Duck");
        Person loulou = new Person("Loulou", "Duck");

        AddressBook contacts1 = new AddressBook(donald, List.of(riri, fifi, loulou));
        AddressBook contacts2 = new AddressBook(riri, List.of(donald, fifi, loulou));

        this.addressBooks.addAll(List.of(contacts1, contacts2));
        this.persons.addAll(List.of(donald, riri, fifi, loulou));
        
        System.out.println("Database seeded");
    }

    public List<Integer> getPersonIds() {
        List<Integer> ids = new ArrayList<>();
        for (Person p : persons) {
            ids.add(p.getId());
        }
        return ids;
    }

    public Person getPersonById(int id) {
        for (Person person : persons) {
            if (person.getId() == id) return person;
        }

        return null; // we could also throw an error
    }

    public Person createPerson(String firstname, String lastname) {
        Person p = new Person(firstname, lastname);
        persons.add(p);

        return p;
    }

    public boolean deletePerson(Person p) {
        return persons.remove(p);
    }

    public AddressBook getAddressBookById(int id) {
        for (AddressBook addressBook : addressBooks) {
            if (addressBook.getId() == id) return addressBook;
        }

        return null; // we could also throw an error
    }

    public List<Integer> getAddressBooksIds() {
        List<Integer> ids = new ArrayList<>();
        for (AddressBook p : addressBooks) {
            ids.add(p.getId());
        }
        return ids;
    }

    public AddressBook createAddressBook(Person owner, List<Person> persons) {
        AddressBook a = new AddressBook(owner, persons);
        addressBooks.add(a);
        return a;
    }

    public boolean deleteAddressBook(AddressBook a) {
        return addressBooks.remove(a);
    }
}
