#include <stddef.h>
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include "mesh.h"

#include <stdlib.h>

#include "array.h"

mesh_t mesh = {
    .vertices = NULL,
    .faces = NULL,
    .rotation = { 0, 0, 0 },
    .scale = { 1.0, 1.0, 1.0 },
    .translation = { 0, 0, 0 },
};

vec3_t cube_vertices[N_CUBE_VERTICES] = {
    { .x = -1, .y = -1, .z = -1 }, // 1
    { .x = -1, .y =  1, .z = -1 }, // 2
    { .x =  1, .y =  1, .z = -1 }, // 3
    { .x =  1, .y = -1, .z = -1 }, // 4
    { .x =  1, .y =  1, .z =  1 }, // 5
    { .x =  1, .y = -1, .z =  1 }, // 6
    { .x = -1, .y =  1, .z =  1 }, // 7
    { .x = -1, .y = -1, .z =  1 }  // 8
};

face_t cube_faces[N_CUBE_FACES] = {
    // front
    { .a = 1, .b = 2, .c = 3 , .color = COLOR_ORANGE},
    { .a = 1, .b = 3, .c = 4, .color  = COLOR_ORANGE},
    // right
    { .a = 4, .b = 3, .c = 5, .color = COLOR_TEAL_GREEN },
    { .a = 4, .b = 5, .c = 6, .color = COLOR_TEAL_GREEN},
    // back
    { .a = 6, .b = 5, .c = 7, .color = COLOR_RED },
    { .a = 6, .b = 7, .c = 8, .color = COLOR_RED },
    // left
    { .a = 8, .b = 7, .c = 2, .color = COLOR_PURPLE },
    { .a = 8, .b = 2, .c = 1, .color = COLOR_PURPLE },
    // top
    { .a = 2, .b = 7, .c = 5, .color = COLOR_GREY },
    { .a = 2, .b = 5, .c = 3, .color = COLOR_GREY },
    // bottom
    { .a = 6, .b = 8, .c = 1, .color = COLOR_LIGHT_GREEN_BLUE },
    { .a = 6, .b = 1, .c = 4, .color = COLOR_LIGHT_GREEN_BLUE }
};

void load_cube_mesh_data(void) {
    for (int i = 0; i < N_CUBE_VERTICES; i++) {
        array_push(mesh.vertices, cube_vertices[i]);
    }
    for (int i = 0; i < N_CUBE_FACES; i++) {
        array_push(mesh.faces, cube_faces[i]);
    }
}

void parse_face(const char* buffer, face_t* face) {
    char temp_a[64], temp_b[64], temp_c[64];
    sscanf(buffer, "f %63s %63s %63s", temp_a, temp_b, temp_c);

    char* token;

    token = strtok(temp_a, "/");
    face->a = token ? atoi(token) : -1;

    token = strtok(temp_b, "/");
    face->b = token ? atoi(token) : -1;

    token = strtok(temp_c, "/");
    face->c = token ? atoi(token) : -1;
}

void load_file(const char* filename) {
    FILE* fp;
    char* tok;

    fp = fopen(filename, "r");

    if (fp == NULL) {
        exit(EXIT_FAILURE);
    }

    char buffer[MAX_LEN];
    while (fgets(buffer, MAX_LEN, fp)) {

        if (strncmp(buffer, "v ", 2) == 0) {
            vec3_t vertex;
            sscanf(buffer, "v %f %f %f", &vertex.x, &vertex.y, &vertex.z);

            array_push(mesh.vertices, vertex);

        } else if (strncmp(buffer, "f ", 2) == 0) {
            face_t face;

            parse_face(buffer, &face);

            array_push(mesh.faces, face);

        }
        printf("\n");
    }

    fflush(stdout);
    fclose(fp);

}