#include <stdio.h>
#include <stdbool.h>
#include <glib.h>
#include "csv.h"

int bot_get_current_entry_id_csv
(
 const GString* filename
)
{
    /* TODO this counts by char, probably more efficient ways exist */
    char c;
    FILE *fp;
    unsigned int count = 0;

    if((fp = fopen(filename->str, "r"))) {
        for (c = getc(fp); c != EOF; c = getc(fp)) {
            if (c == '\n') {
                count++;
            }
        }
        fclose(fp);
    }

    return count;
}

/* returns the number of bytes written, following the convention of fprintf.
 * Returns negative in case of error
 */
int write_bot_expense_entry
(
 const GString *filename,
 BotExpenseEntry *entry,
 bool needsHeaders
)
{
    FILE *fp;
    int result;
    GString *line = serialize_bot_expense_entry_csv(entry);

    if(line == NULL) {
        return -1;
    }

    if((fp = fopen(filename->str, "a"))) {
        if(needsHeaders) {
            fprintf(fp, "ID,Time,Value,User,Notes\n");
        }

        /* line is terminated with '\n' */
        result = fprintf(fp, "%s", line->str);
        fclose(fp);

        return result;
        fprintf(stderr, "Error opening %s\n", filename->str);
    }

    fprintf(stderr, "Error opening %s\n", filename->str);
    return -1;
}

/* whole routine to write an expense to a CSV file */
int write_update_to_csv
(
 const GString *filename,
 const BotCommand cmd,
 const double value,
 GString* user,
 GString* notes
)
{
    int result;
    unsigned int id;
    BotExpenseEntry *entry;
    BotExpenseEntry *previous = bot_get_last_expense();

    id = (previous == NULL) ? bot_get_current_entry_id_csv(filename) : previous->id + 1;

    entry = create_bot_expense_entry(previous, id, cmd, value, user, notes);
    if(entry == NULL) {
        return -1;
    }

    /* if no ID, empty file, initialize with headers before writing entry */
    result = write_bot_expense_entry(filename, entry, (id == 0));

    if(result > 0) {  /* write successful */
        bot_set_last_command(cmd);
        bot_set_last_expense(entry);
    }
    return result;
}
