package fr.imta.addressbook.model;

import io.vertx.core.json.JsonObject;

public class Person {
    private static int NEXT_ID = 0;
    private int id;
    private String firstName;
    private String lastName;
    private AddressBook addressBook;

    public Person() {}

    public Person(String firstName, String lastName) {
        this.id = NEXT_ID++;
        this.firstName = firstName;
        this.lastName = lastName;
    }
    public int getId() {
        return id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public AddressBook getAddressBook() {
        return addressBook;
    }

    public void setAddressBook(AddressBook addressBook) {
        AddressBook previousAddressBook = this.addressBook;
        if (this.addressBook != addressBook) {
            this.addressBook = null;
            if (previousAddressBook != null) {
                previousAddressBook.setOwner(null);
            }
            if (addressBook != null) {
                this.addressBook = addressBook;
                addressBook.setOwner(this);
            }
        }
    }
    
    public JsonObject toJSON() {
        JsonObject result = new JsonObject();

        result.put("id", id);
        result.put("firstname", firstName);
        result.put("lastname", lastName);

        if (this.addressBook == null) {
            result.put("addressbook", null);
        }
        else {
            result.put("addressbook", addressBook.getId());
        }

        return result;
    }
}
