#include <cstddef>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include  <bits/stdc++.h>
#include <ostream>
#include <sstream>
#include <string>
#include "../include/PhoneBook.hpp"

int get_input(std::string &in, std::string out)
{
	while (in.size() == 0)
	{
		std::cout << out;
		if (!std::getline(std::cin, in))
			return (1);
	}
	return (0);
}

Contact* read_contact()
{
	std::string	first_name;
	std::string	last_name;
	std::string	nickname;
	std::string	phone_number;
	std::string	darkest_secret;

	if (get_input(first_name, "first_name: ")
			|| get_input(last_name, "last_name: ")
			|| get_input(nickname, "nickname: ")
			|| get_input(phone_number, "phone_number: ")
			|| get_input(darkest_secret, "darkest_secret: "))
		return (NULL);

	return (new Contact(first_name, last_name, nickname, phone_number, darkest_secret));
}

Contact*	search(PhoneBook &phone_book)
{
	int				index;
	std::string		index_str;
	Contact*		contact;

	contact = NULL;
	while (contact == NULL)
	{
		if (get_input(index_str, "index: "))
			return (NULL);
		index = std::atoi(index_str.c_str());
		contact = phone_book.search(index);
	}
	return (contact);
}

int	main()
{
	std::string			command;
	Contact*			contact;
	PhoneBook			phone_book;

	while (true)
	{
		std::cout << "command: ";
		if (!std::getline(std::cin, command))
			return (0);
		if (command == "ADD")
		{
			contact = read_contact();
			if (contact == NULL)
				return (0);
			phone_book.add_contact(contact);
		}
		else if (command == "SEARCH")
		{
			phone_book.display_contacts();
			if (phone_book.len > 0)
			{
				contact = search(phone_book);
				if (contact == NULL)
					return (0);
				std::cout << contact->to_string_complete() << std::endl;
			}
		}
		else if (command == "EXIT")
		{
			return (0);
		}
		else {
			std::cerr << "Command not found" << std::endl;
		}
	}
	return (0);
}
