#include <stdlib.h>
#include <stdio.h>
#include <graph.h>

int lireScore()
{
    int score;
    FILE* fichier = fopen("score.txt", "r");
    if (fichier == NULL)
    {
        fprintf(stderr, "Le fichier score.txt n'existe pas. Création du fichier avec la valeur 0.\n");

        score = 0;

        /* Ouvrir le fichier en mode écriture pour créer le fichier s'il n'existe pas */
        fichier = fopen("score.txt", "w");
        if (fichier == NULL)
        {
            fprintf(stderr, "Erreur lors de la création du fichier score.txt\n");
            return -1;
        }

        /* Écrire la valeur 0 par défaut */
        fprintf(fichier, "%d\n", score);

        fclose(fichier);
        return score;
    }

    fscanf(fichier, "%d", &score);
    fclose(fichier);
    return score;
}

void sauvegarderScore(unsigned long nouveauScore)
{
    FILE* fichier = fopen("score.txt", "w");
    if (fichier == NULL)
    {
        fprintf(stderr, "Erreur lors de l'ouverture du fichier score.txt \n");
        return;
    }

    fprintf(fichier, "%ld\n", nouveauScore);

    fclose(fichier);
}

void CheckScore(unsigned long nouveauScore)
{
    unsigned long scoreActuel = lireScore();

    if (nouveauScore > scoreActuel || scoreActuel == 0)
    {
        sauvegarderScore(nouveauScore);
        /* printf("Le score a été enregistré avec succès.\n");  DEBUG */
    }
   /* else
    {
        printf("Le score précédent est plus grand ou égal.\n");
    }                                                               DEBUG
    */ 
}

void Menu()
{
    char buf[100];
    couleur text;
    unsigned long bestscore = lireScore();
    text=CouleurParComposante(78, 93, 47);
    ChoisirEcran(0);
    ChargerImage("./images/Menu.png",0,0,0,0,930,710); 
    ChoisirCouleurDessin(text);
    snprintf(buf,100,"MEILLEUR SCORE : %07ld",bestscore);
	EcrireTexte(420,350,buf,2);
}

void Pause()
{   
    ChoisirEcran(0);
    ChargerImage("./images/Pause.png",0,0,0,0,930,710);

}

void PerduGUI()
{
    char buf[100];
    unsigned long bestscore = lireScore();
    ChoisirEcran(0);
    ChargerImage("./images/Perdu.png",0,0,0,0,930,710);
    snprintf(buf,100,"MEILLEUR SCORE : %07ld",bestscore);
	EcrireTexte(420,350,buf,2);
}

void AfficherTimerEtScore(long unsigned int *score, int minutes,int secondes)   /*Afficher le temps passé et le score*/
{   
    char buf[100];
    char buff[100]; /* Stockage du score et du timer */
    couleur text;
    text=CouleurParComposante(78, 93, 47);

	ChoisirEcran(1);
    CopierZone(2,1,0,0,930,710,0,0);

    ChoisirCouleurDessin(text);
    
	snprintf(buf,100,"TEMPS : %02d:%02d",minutes,secondes);
    snprintf(buff,100,"SCORE : %07ld",*score);
	EcrireTexte(60,695,buf,2);
    EcrireTexte(600,695,buff,2);

	CopierZone(1,0,0,0,930,710,0,0);
}