/***************************** LICENSE START ***********************************

 Copyright 2012 ECMWF and INPE. This software is distributed under the terms
 of the Apache License version 2.0. In applying this license, ECMWF does not
 waive the privileges and immunities granted to it by virtue of its status as
 an Intergovernmental Organization or submit itself to any jurisdiction.

 ***************************** LICENSE END *************************************/

#include <cstdio>
#include <strings.h>

#include "MvQFileWatcher.h"

#include <QFileSystemWatcher>

MvQFileWatcher::MvQFileWatcher() :
    file_(nullptr),
    watcher_(nullptr)
{
}

MvQFileWatcher::~MvQFileWatcher()
{
    stop();
}

void MvQFileWatcher::stop()
{
    if (file_) {
        if (watcher_) {
            delete watcher_;
            watcher_ = nullptr;
        }

        file_ = nullptr;
    }
}

void MvQFileWatcher::start(FILE* f, const std::string& path)
{
    if (file_ == nullptr && f != nullptr) {
        file_ = f;

        // int n=fileno(f);

        if (!watcher_) {
            watcher_ = new QFileSystemWatcher(this);
            watcher_->addPath(QString::fromStdString(path));

            connect(watcher_, SIGNAL(fileChanged(const QString&)),
                    this, SLOT(slotInput(const QString&)));
        }
    }
}


void MvQFileWatcher::slotInput(const QString&)
{
    char buf[1024];

    fflush(file_);

    if (fgets(buf, sizeof(buf), file_)) {
        if (buf[0])
            buf[strlen(buf) - 1] = 0;
        emit ready(buf);
    }
    // else
    //	emit done(file_);
}
