/**
 *
 * @file plugins/CriticalPath/ParseTasks.cpp
 *
 * @copyright 2008-2024 Bordeaux INP, CNRS (LaBRI UMR 5800), Inria,
 *                      Univ. Bordeaux. All rights reserved.
 *
 * @author Camille Ordronneau
 * @author Johnny Jazeix
 * @author Mathieu Faverge
 *
 * @date 2024-07-17
 */
#include "ParseTasks.hpp"
#include "assert.h"

using namespace std;

void insert_element(std::vector<double> &t, size_t index, double to_insert) {
    if (t.size() <= index) {
        t.resize(index + 1, 0);
    }
    t.insert(t.begin() + index, to_insert);
}

int parse_task(string &filename, std::vector<double> &t) {
    ifstream input;
    input.open(filename);

    int job_id = -1;
    double start_time = -1;
    double end_time;

    if (!input.is_open()) {
        return -1;
    }

    while (input) {
        string line;
        getline(input, line, ':');

        if (line.compare("JobId") == 0) {
            /* If a task has a start time but the end time is missing */
            assert(start_time == -1 || job_id == -1);
            start_time = -1;
            end_time = 0;
            input >> job_id;
        }

        if (line.compare("StartTime") == 0) {
            /* To ensure getting the start time of a new event */
            assert(start_time == -1 && job_id != -1);
            input >> start_time;
        }

        if (line.compare("EndTime") == 0) {
            /* To ensure the start time of the new event is initialized */
            assert(start_time != -1 && job_id != -1);
            input >> end_time;
            insert_element(t, job_id, end_time - start_time);
            job_id = -1;
        }

        getline(input, line, '\n');
    }

    input.close();
    return 0;
}

double get_time(int jobId, std::vector<double> &t) {
    return t[jobId];
}
