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

 Copyright 2014 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 "MvQFolderWatcher.h"

#include <QDebug>
#include <QFileSystemWatcher>
#include <QTimer>

#include "Folder.h"
#include "FolderPresenter.h"

QList<MvQFolderWatcher*> MvQFolderWatcher::items_;
QMap<Folder*, MvQTimeoutInfo> MvQFolderWatcher::timeoutLog_;
int MvQFolderWatcher::timeout_ = 500;

MvQFolderWatcher::MvQFolderWatcher(FolderPresenter* fp) :
    presenter_(fp)
{
    fsWatcher_ = new QFileSystemWatcher(this);

    if (Folder* f = folder()) {
        fsWatcher_->addPath(QString::fromStdString(f->path().str()));
    }

    connect(fsWatcher_, SIGNAL(directoryChanged(QString)),
            this, SLOT(slotFolderChanged(QString)));

    Q_ASSERT(presenter_->realObject());
    connect(presenter_->realObject(), SIGNAL(pathChanged()),
            this, SLOT(slotFolderPathChanged()));

    timer_ = new QTimer(this);

    items_ << this;
}

Folder* MvQFolderWatcher::folder()
{
    return presenter_->currentFolder();
}


void MvQFolderWatcher::cleanLog()
{
    QList<Folder*> lst;
    foreach (MvQFolderWatcher* item, items_) {
        lst << item->folder();
    }

    QList<Folder*> keys = timeoutLog_.keys();
    foreach (Folder* f, keys) {
        if (!lst.contains(f))
            timeoutLog_.remove(f);
    }
}

// anew file was addedd/removed in the folder
void MvQFolderWatcher::slotFolderChanged(QString)
{
    if (Folder* f = folder()) {
        if (!fsWatcher_->directories().contains(QString::fromStdString(f->path().str()))) {
            slotFolderPathChanged();
            return;
        }
    }

    //we delay the rescan. With an immediate rescan a new file being written (and thus empty or
    //not yet complete ) can be interpreted as NOTE by Desktop!
    timer_->singleShot(timeout_, this, SLOT(slotTimeout()));
    //reload();
}

void MvQFolderWatcher::slotFolderPathChanged()
{
    //clear the fswatcher
    fsWatcher_->removePaths(fsWatcher_->directories());
    if (Folder* f = folder()) {
        fsWatcher_->addPath(QString::fromStdString(f->path().str()));
        //f->scan();
    }
}

void MvQFolderWatcher::slotTimeout()
{
    reload();
}

void MvQFolderWatcher::reload()
{
    if (Folder* f = folder()) {
        f->scan();
    }
    //print();
}

MvQFolderWatcher* MvQFolderWatcher::add(FolderPresenter* fp)
{
    MvQFolderWatcher* item = find(fp);
    if (!item) {
        cleanLog();
        item = new MvQFolderWatcher(fp);
    }

    return item;
}

void MvQFolderWatcher::remove(FolderPresenter* fp)
{
    if (MvQFolderWatcher* item = find(fp)) {
        items_.removeAll(item);
        delete item;
        cleanLog();
    }
}

void MvQFolderWatcher::reload(FolderPresenter* fp)
{
    MvQFolderWatcher* item = find(fp);
    if (item) {
        item->reload();
    }
    //safety measure
    else {
        item = MvQFolderWatcher::add(fp);
        item->reload();
    }
}

MvQFolderWatcher* MvQFolderWatcher::find(FolderPresenter* fp)
{
    foreach (MvQFolderWatcher* item, items_) {
        if (item->folderPresenter() == fp)
            return item;
    }
    return NULL;
}

void MvQFolderWatcher::print()
{
    qDebug() << "Watched folders: \n----------------";
    foreach (MvQFolderWatcher* item, items_) {
        qDebug() << QString::fromStdString(item->folder()->fullName()) << timeout_ / 1000 << "s";
    }
}
