#include "Dictionnaire.h"
#include <fstream>
#include <stdexcept>
#include <iostream>

Dictionnaire::Dictionnaire(const std::string& nomFichier)
{
    std::ifstream f(nomFichier);
    if (!f.is_open())
        throw std::runtime_error("Impossible d'ouvrir le fichier : " + nomFichier);

    int n = 0;
    f >> n;
    if (!f)
        throw std::runtime_error("Fichier dictionnaire invalide (première ligne).");

    _tuiles.reserve(n);

    
    
    for (int i = 0; i < n; ++i)
    {
        std::string nom, prop;
        int x = 0, y = 0;

        f >> nom >> x >> y >> prop;
        if (!f)
            throw std::runtime_error("Erreur de lecture : ligne " + std::to_string(i + 1));

        _tuiles.emplace_back(nom, x, y, prop);
    }
}

void Dictionnaire::afficher() const
{
    for (const Tuile& t : _tuiles)
        t.afficher();
}

bool Dictionnaire::recherche(const std::string& nomRecherche, Tuile& resultat) const
{
    
    int gauche = 0;
    int droite = static_cast<int>(_tuiles.size()) - 1;

    while (gauche <= droite)
    {
        int milieu = gauche + (droite - gauche) / 2;
        const std::string& nomMilieu = _tuiles[milieu].getNom();

        if (nomMilieu == nomRecherche)
        {
            resultat = _tuiles[milieu]; 
            return true;
        }
        else if (nomMilieu < nomRecherche)
        {
            gauche = milieu + 1;
        }
        else
        {
            droite = milieu - 1;
        }
    }

    return false;
}

int Dictionnaire::taille() const
{
    return static_cast<int>(_tuiles.size());
}
