//
//  main.c
//  labyrinthe
//
//  Created by léo LELLOUCHE on 15/03/2016.
//  Copyright © 2016 léo LELLOUCHE. All rights reserved.
//

#include "header.h"

char    **nouvelle_partie(int *fd, int *size_tab, int *size_path, t_list **path)
{
    char    **labyrinthe;
    
    *size_tab = scanf_size();
    *path = (t_list *)malloc(sizeof(t_list));
    labyrinthe = generation(*size_tab, *path, size_path);
    save_path(**path, fd[1]);
    // leaks();
    // La fonction génération génère 1 leaks !
    
    print_tab(labyrinthe, 0, fd[0]);
    return (labyrinthe);
}

void    malloc_2d(char **tab, int height_size, int width_size, int i)
{
    if (i < height_size)
    {
        tab[i] = malloc(sizeof(char) * width_size);
        malloc_2d(tab, height_size, width_size, i + 1);
    }
    
}

int     main(void)
{
    char    **labyrinthe;
    char    **current_affichage;
    int     size_tab;
    int     size_path;
    int     *fd;
    int     *choix;
    int     ret;
    t_point depart;
    t_list  *path;
    t_vie   vie;
    
    ft_clear();
    printf("Bienvenue\n");
    choix = choix_initiaux();
    fd = ouverture_fichiers(choix[0]);
    srand((unsigned int)time(NULL));
    ret = 0;
    
    if (choix[0] == 1)
    {
        labyrinthe = nouvelle_partie(fd, &size_tab, &size_path, &path);
        if (choix[1] == 1)
        {
            depart.line = 1;
            depart.col = 1;
            init_play(&vie, size_tab);
            dprintf(fd[3], "%d\n", size_tab);
            dprintf(fd[3], "%d", size_path);
            ret = play(labyrinthe, size_tab, fd, NULL, depart, vie);
        }
        else
            resolution(path, labyrinthe);
    }
    else
    {
        path = reprise_partie(&labyrinthe, &size_tab, path, &depart, &vie, &current_affichage, fd);
        if (choix[1] == 1)
            ret = play(labyrinthe, size_tab, fd, current_affichage, depart, vie);
        else
            resolution(path, labyrinthe);
    }
    if (ret == -1)
    {
        printf("Voulez-vous voir la solution ?\n");
        printf(" 1. Non\n");
        printf(" 2. Oui\n");
        scanf("%d", &choix[1]);
        if (choix[1] == 2)
            resolution(path, labyrinthe);
    }
    else
    {
        printf("-----------------------\n");
        printf("|  Felicitation !!!!  |\n");
        printf("|  Vous avez gagné !  |\n");
        printf("-----------------------\n");
    }
    close(fd[0]);
    close(fd[1]);
    close(fd[2]);
    close(fd[3]);
    close(fd[4]);
    close(fd[5]);
    return (0);
}