#include <stddef.h>
#include <stdlib.h>
#include "vector.h"
#include <stdio.h>
#include <strings.h>
#include "animals.h"
struct vector *vector_init(size_t n){

    //if (n < 0) return NULL;
    struct vector *vector = malloc(sizeof(struct vector));

    vector->animal = malloc((n) * sizeof(struct animal));
    if(vector->animal == NULL) return NULL;

    vector->capacity = n;
    vector->size = 0;

    return vector;
}

struct vector *vector_resize(struct vector *v, size_t new_capacity){

    if(v == NULL) return NULL;
   
    v->animal = realloc(v->animal, (new_capacity + 1) * sizeof(struct animal));
    v->capacity = new_capacity;

    return v;
    
}

struct vector *vector_append(struct vector *v, struct animal *animal){

    if(v == NULL || animal == NULL) return NULL;
    
    if (v->capacity <= v->size) v = vector_resize(v, v->capacity * 2);
    // TODO A voir si le realloc ajoute de l'espace a gauche ou a droite
    // car sinon y a ecrasement de data
    *(v->animal + (v->capacity - v->size )) = animal;
    v->size ++;
    return v;
}

void free_animal(struct animal *animal){

    if (animal == NULL) return;

    //if(animal->color != NULL) free(animal->color);
    printf("%s\n",animal->animal.fish->species); 
    printf("%s\n", animal->animal.insect->species);
    if(animal->type == INSECT) free_insect(animal->animal.insect);
    if(animal->type == FISH) free_fish(animal->animal.fish);
    free(animal->color);
    free(animal);
}

void vector_destroy(struct vector *v){

    if(v == NULL) return;
    if(v->animal != NULL){
    
    //size_t index = 1;
    /*while (index < (v->capacity - v->size)){
        free_animal(*(v->animal + (v->size - index)));
    }*/
        for(size_t i = 0; i < v->size; i++) free_animal(v->animal[i]);
    }

    free(v->animal);
    free(v);
    //free_animal(v->animal);
}
