//
//  reprise_partie.c
//  labyrinthe
//
//  Created by léo LELLOUCHE on 12/04/2016.
//  Copyright © 2016 léo LELLOUCHE. All rights reserved.
//

#include "header.h"

static  void    recup_dimensions(int *size_tab, int *size_path, int *fd)
{
    char **tmp_sizes;
 
    tmp_sizes = malloc(sizeof(char *) * 2);
    malloc_2d(tmp_sizes, 2, 4, 0);
    lecture_fichier(fd[3], tmp_sizes);
    
    *size_tab = atoi(tmp_sizes[0]);
    *size_path = atoi(tmp_sizes[1]);
    free_2d(tmp_sizes, 0, 2);
    free(tmp_sizes);
}

static  char    **recup_labyrinthe(int size_tab, int *fd)
{
    char **labyrinthe;
    
    labyrinthe = malloc(sizeof(char *) * (size_tab));
    malloc_2d(labyrinthe, size_tab, (2 * (size_tab)) + 4, 0);
    lecture_fichier(fd[0], labyrinthe);
    return (labyrinthe);
}

static  char    **recup_affichage(int size_tab, int *fd)
{
    char **current_affichage;
    
    current_affichage = malloc(sizeof(char *) * size_tab);
    malloc_2d(current_affichage, size_tab, (2 * size_tab) + 4, 0);
    lecture_fichier(fd[4], current_affichage);
    
    if (current_affichage[0][0] != MUR_EXT)
    {
        free_2d(current_affichage, 0, size_tab);
        free(current_affichage);
        current_affichage = NULL;
    }
    return (current_affichage);
}

static t_list    *recup_path(int size_path, t_list *path, int *fd)
{
    char    **tmp_path;
    
    tmp_path = malloc(sizeof(char *) * size_path);
    malloc_2d(tmp_path, size_path, 7, 0);
    
    lecture_fichier(fd[1], tmp_path);
    path = malloc(sizeof(t_list));
    path->line = atoi(tmp_path[0]);
    path->col = atoi(tmp_path[1]);
    tmp_path_to_t_list(path, tmp_path, size_path);
    free_2d(tmp_path, 0, size_path);
    free(tmp_path);
    return (path);
}

static  void    recup_position(t_point *position, int *fd)
{
    char **tmp_position;
    
    tmp_position = malloc(sizeof(char *) * 2);
    malloc_2d(tmp_position, 2, 5, 0);
    
    lecture_fichier(fd[2], tmp_position);
    
    position->line = atoi(tmp_position[0]);
    position->col = atoi(tmp_position[1]);
    
    free_2d(tmp_position, 0, 2);
    free(tmp_position);
}

static  void    recup_vie(t_vie *vie, int *fd)
{
    char **tmp_vie;
    
    tmp_vie = malloc(sizeof (char *) * 2);
    tmp_vie[0] = malloc(sizeof(char) * 7);
    tmp_vie[1] = malloc(sizeof(char) * 7);
    lecture_fichier(fd[5], tmp_vie);
    vie->restante = atoi(tmp_vie[0]);
    vie->totale = atoi(tmp_vie[1]);
    free(tmp_vie[0]);
    free(tmp_vie[1]);
    free(tmp_vie);
}

// On doit aussi tout free !!
t_list     *reprise_partie(char ***labyrinthe, int *size_tab, t_list *path, t_point *position, t_vie *vie, char ***current_affichage, int *fd)
{
    int     size_path;
    recup_dimensions(size_tab, &size_path, fd);
    *labyrinthe = recup_labyrinthe(*size_tab, fd);
    *current_affichage = recup_affichage(*size_tab, fd);
    path = recup_path(size_path, path, fd);
    
    recup_position(position, fd);
    recup_vie(vie, fd);
    return (path);
}
