package lab06.v2_contactos;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;



public class ContactStorageTXT implements ContactsStorageInterface{
    
    File file;


    public ContactStorageTXT(String filename){
		this.file = new File(filename);
	}

    public boolean saveContacts(List<Contact> list){

        //  if the file doesnt exist all contacts will be saved to a new file
            try {

                if (file.createNewFile()) {
                    FileWriter writer = new FileWriter(file);

                    for (Contact contact : list)
                        writer.write(contact.getName() + ":" + contact.getNumber() + "\t");
                    writer.close();
                }
                
        
        // if file exists, check if the contact already exist, if not add them
                else {
                    Scanner sc = new Scanner(file);
                    FileWriter writer = new FileWriter(file);
                    for (Contact contact : list){
                        boolean found = false;
                        String contactTXT = contact.getName() + ":" + contact.getNumber() + "\t";

                        while (sc.hasNextLine()){
                            String line = sc.nextLine();
                            if(line.equals(contactTXT)){ 
                                found = true;
                                break;
                            }
                        }
                        if (found == false){
                            writer.write(contact.getName() + ":" + contact.getNumber() + "\t");
                        }

                    }
                    sc.close();
                    writer.close();
                } 
            }
                
            catch (IOException e) {
                System.out.println("An error occurred.");
                e.printStackTrace();
                return false;
              }

        return true;
    }
  

    public List<Contact> loadContacts() {

		
    
        List<Contact> contacts = new ArrayList<Contact>();

		try {
			Scanner sc = new Scanner(file);
			while (sc.hasNextLine()) {

				String[] line = sc.nextLine().split("\t");
				for (String nameNumber : line) {
					String[] contact = nameNumber.split(":");
					contacts.add(new Contact(contact[0], Integer.parseInt(contact[1])));
				}
			}

			sc.close();

		} 
        
        catch (FileNotFoundException e) {
			System.out.println("Contacts file not found");
		}

		return contacts;
	}
}

