package lab06.v2_contactos;

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

public class ContactsOperations implements ContactsInterface{
        
    private ContactsStorageInterface storage;
    List<Contact> contacts = new ArrayList<>();


    public void openAndLoad(ContactsStorageInterface storage) {
        this.storage = storage;
        this.contacts = storage.loadContacts();

        for (Contact contact : contacts) 
            System.out.println(contact);
    }

    public void saveAndClose() {
        if (storage.saveContacts(contacts) == true){
            contacts.clear();
            System.out.println("Contacts saved successfully!");
        }
        else {
            System.out.println("Error saving contacts. Please try again later.");
            System.exit(1);
        }
    }

    public void saveAndClose(ContactsStorageInterface storage) {
        if (storage.saveContacts(contacts) == true){
            contacts.clear();
            System.out.println("Contacts saved successfully!");
        }
        else {
            System.out.println("Error saving contacts. Please try again later.");
            System.exit(1);
        }
    }

    public boolean exist(Contact contact) {
        for (Contact contactSeatch : contacts) {

            if (contact.toString().equals(contactSeatch.toString()))
                return true;
        }

        return false;
    }

    public Contact getByName(String name) {
        for (Contact contactByName : contacts) {
            if (contactByName.getName().equals(name))
                return contactByName;
        }

        System.out.println("Contact was not found.");
        return null;
    }

    public boolean add(Contact contact) {
        if (contacts.add(contact))
            return true;

        return false;
    }

    public boolean remove(Contact contact) {
        if (contacts.remove(contact))
            return true;

        return false;
    }
}

