package fr.imta.addressbook.model;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;

public class AddressBook {
    private static int NEXT_ID = 0;
    private int id;

    private Person owner;
    private List<Person> persons;

    public AddressBook(Person owner) {
        this(owner, Collections.emptyList());
    }

    public AddressBook(Person owner, Collection<Person> persons) {
        this.id = NEXT_ID++;
        this.persons = new ArrayList<>(persons);
        setOwner(owner);
    }

    public int getId() {
        return id;
    }

    public Person getOwner() {
        return owner;
    }

    public void setOwner(Person owner) {
        Person previousOwner = this.owner;
        if (owner != this.owner) {
            this.owner = null;
            if (previousOwner != null) {
                previousOwner.setAddressBook(null);
            }
            if (owner != null) {
                this.owner = owner;
                this.owner.setAddressBook(this);
            }
        }
    }

    public List<Person> getPersons() {
        return persons;
    }

    public JsonObject toJSON() {
        JsonObject result = new JsonObject();

        result.put("id", id);
        if (owner == null)
            result.put("owner", null);
        else
            result.put("owner", owner.getId());

        JsonArray contactsIDs = new JsonArray();
        for (Person p : persons) {
            contactsIDs.add(p.getId());
        }
        result.put("persons", contactsIDs);

        return result;
    }

}
