/**
 *
 * @file src/trace/SerializerWriter.cpp
 *
 * @copyright 2008-2024 Bordeaux INP, CNRS (LaBRI UMR 5800), Inria,
 *                      Univ. Bordeaux. All rights reserved.
 *
 * @author Camille Ordronneau
 * @author Johnny Jazeix
 * @author Augustin Degomme
 *
 * @date 2024-07-17
 */

#include <iostream>
#include <string>
#include <map>
#include <list>
#include <vector>
#include <sstream>
#include <stack>
#include <algorithm>
#include <QWaitCondition>
#include <QObject>
#include <QMutex>
#include <QThread>
#include <QSemaphore>
/* -- */

#include "trace/values/Values.hpp"
#include "trace/EntityValue.hpp"
#include "trace/EntityTypes.hpp"
#include "trace/Entitys.hpp"
#include "trace/Trace.hpp"
#include "trace/tree/Node.hpp"
#include "trace/tree/BinaryTree.hpp"
/* -- */
#include "common/common.hpp"
#include "common/Info.hpp"
#include "common/Message.hpp"
/* -- */
#include "trace/tree/Interval.hpp"
#include <trace/SerializerWriter.hpp>
// static map<string, Value *> opt_test;

SerializerWriter::SerializerWriter() :
    _cond(NULL), _freeSlots(NULL), _itcProduced(NULL), _thread(NULL) {
}
SerializerWriter::SerializerWriter(QWaitCondition *cond, QSemaphore *freeSlots, QSemaphore *itcProduced, QThread *thread, QMutex *mutex) {
    _cond = cond;
    _freeSlots = freeSlots;
    _itcProduced = itcProduced;
    _thread = thread;
    _mutex = mutex;
}
/*
void SerializerWriter::set_values(QWaitCondition* cond, QSemaphore* freeSlots, QSemaphore* itcProduced, QThread* thread){
_cond=cond;
_freeSlots=freeSlots;
_itcProduced=itcProduced;
_thread=thread;
}*/

QWaitCondition *SerializerWriter::get_cond() {
    return _cond;
}

QSemaphore *SerializerWriter::get_sem_free() {
    return _freeSlots;
}
QSemaphore *SerializerWriter::get_sem_produced() {
    return _itcProduced;
}

QThread *SerializerWriter::get_thread() {
    return _thread;
}

void SerializerWriter::dump_on_disk(IntervalOfContainer *itc, char *filename) {
    _freeSlots->acquire();
    itc->dump_on_disk(filename);
    itc->unload();
    _itcProduced->release();
    free(filename);
}

void SerializerWriter::load(IntervalOfContainer *itc, char *filename) {
    _freeSlots->acquire();
    itc->retrieve(filename);
    _itcProduced->release();
    free(filename);
}

bool SerializerWriter::is_finished() { return _is_finished; }
void SerializerWriter::finish_build() {
    //  printf("répondons : %p _this %p %p\n", _thread,this, _cond);
    // locks the mutex and automatically unlocks it when going out of scope
    QMutexLocker locker(_mutex);
    _is_finished = true;
    _cond->wakeAll();
}

#include "moc_SerializerWriter.cpp"
