#include <cstddef>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include  <bits/stdc++.h>
#include <ostream>
#include <sstream>
#include <string>
#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);
}

int read_contact(Contact& 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 (1);
	Contact new_contact = Contact(first_name, last_name, nickname, phone_number, darkest_secret);
	contact = new_contact;
	return (0);
}

int	isdigit(std::string& str)
{
	for (size_t i = 0; i < str.size(); i++)
	{
		if (!std::isdigit(str[i]))
			return(0);
		std::cout << i << std::endl;
	}
	return (1);
}

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

	contact = NULL;
	while (contact == NULL)
	{
		index_str = "";
		if (get_input(index_str, "index: "))
			return (NULL);
		index = std::strtol(index_str.c_str(), &error, 10);
		if (errno == ERANGE || error[0] != '\0')
		{
			std::cerr << "Invalid input" << std::endl;
			errno = 0;
		}
		else {
			contact = phone_book.search(index);
			if (contact == NULL)
				std::cerr << "Contact not found" << std::endl;
		}
	}
	return (contact);
}

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

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