#include "csv_handler.h"

//loads the csv file into the linked list
head *load_csv(const char *filepath){
    FILE* file = fopen(filepath, "r");
    char line [EXPECTED_LINE_LENGTH];
    head* new = NULL;
    new = (head*) malloc(sizeof(*new));
    new -> start = NULL;
    node* nd = new->start;
    while(fgets(line, EXPECTED_LINE_LENGTH, file)){

        if (nd == NULL)
        {
            char *tmp = strdup(line);
            char* tok = strtok(tmp, ",");
            char* filename = strdup(tok);
            tok = strtok(NULL, ",");
            char* url = strdup(tok);
            url[strlen(url)-1] = '\0';
            new -> start = insert(new->start, url, filename, 0);
            nd = new -> start;
            free(tmp);
        }
        else{
            char *tmp = strdup(line);
            char* tok = strtok(tmp, ",");
            char* filename = strdup(tok);
            tok = strtok(NULL, ",");
            char* url = strdup(tok);
            url[strlen(url)-1] = '\0';
            nd = insert(nd, url, filename, 0);
            free(tmp);
        }
        
    }

    fclose(file);

    return new;

}


//inserts the value in the next node or the current node if it is the start
node *insert(node* nd, char* url, char* filename, int valid){
    if (nd == NULL){
        nd = (node *) malloc(sizeof(*(nd->next)));
        nd->url = url;
        nd->filename = filename;
        nd-> next = NULL;

        return nd;

    }

    else{
        node* temp = nd->next;
        nd->next = (node *)malloc(sizeof(*(nd->next)));
        (nd->next)->url = url;
        (nd->next)->filename = filename;
        (nd->next)-> next = temp;

        return nd->next; 
    }

    return NULL;
}

//cleanup the linked list
void delete_list(head* hd){
    if (hd == NULL)
    {
        return;
    }

    else if(hd->start == NULL){
        free(hd);
        return;
    }

    else{
        node* temp = (hd->start)->next;
        free(hd->start->url);
        free(hd->start->filename);
        free(hd->start);
        hd->start = temp;
        delete_list(hd);
        return;
    }
}


void output_csv(char* filepath, head* hd){
    FILE* file = fopen(filepath, "w");

    node *start = hd->start;

    while(start != NULL){
        fprintf(file, "%s,%s,%d\n", start->filename, start->url, start->valid);
        start = start->next;
    }

    fclose(file);
}