/***************************************************************************
**
**  This file is part of GeopsyGui.
**
**  This library is free software; you can redistribute it and/or
**  modify it under the terms of the GNU Lesser General Public
**  License as published by the Free Software Foundation; either
**  version 2.1 of the License, or (at your option) any later version.
**
**  This file is distributed in the hope that it will be useful, but WITHOUT
**  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
**  FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
**  License for more details.
**
**  You should have received a copy of the GNU Lesser General Public
**  License along with this library; if not, write to the Free Software
**  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
**
**  See http://www.geopsy.org for more information.
**
**  Created: 2007-10-21
**  Copyright: 2007-2019
**    Marc Wathelet
**    Marc Wathelet (LGIT, Grenoble, France)
**
***************************************************************************/

#include <GeopsyCore.h>
#include <QGpCoreTools.h>
#include <QGpGuiTools.h>
#include "DirectoryMonitor.h"

namespace GeopsyGui {

/*!
  \class DirectoryMonitor DirectoryMonitor.h
  \brief Brief description of class still missing

  Full description of class still missing
*/

/*!
  Description of constructor still missing
*/
DirectoryMonitor::DirectoryMonitor(QWidget * parent)
    : QWidget(parent)
{
  TRACE;
  setAttribute(Qt::WA_DeleteOnClose, true);
  setupUi(this);

  connect(&_timer, SIGNAL(timeout()), this, SLOT(checkForNewFiles()));
  status->setText(tr("Not active"));

  _db=nullptr;
  _loadedCount=0;

  Settings::getWidget(this, "DirectoryMonitor" );
}

DirectoryMonitor::~DirectoryMonitor()
{
  TRACE;
  if(_timer.isActive()) {
    _timer.stop();
  }
  Settings::setWidget(this, "DirectoryMonitor" );
}

/*!
  Called when the user closes the current database
*/
void DirectoryMonitor::removeAllFiles()
{
  _fileMap.clear();
  _loadedCount=0;
  showStatus();
}

/*!
  Called when the user remove a file from database
*/
void DirectoryMonitor::removeFile(QString path)
{
  if(_fileMap.contains(path)) {
    _fileMap.remove(path);
    _loadedCount--;
    showStatus();
  }
}

void DirectoryMonitor::showStatus()
{
  if(_timer.isActive())
    status->setText(tr("Active: %1/%2 files loaded").arg(_loadedCount).arg(_fileMap.count()));
  else
    status->setText(tr("Not active"));
}

void DirectoryMonitor::on_dirButton_clicked()
{
  TRACE;
  QString s=Message::getExistingDirectory(tr("Directory to monitor"), dir->text());
  if(s.length() > 0) dir->setText(s);
}

void DirectoryMonitor::on_startButton_clicked()
{
  TRACE;
  if(_timer.isActive()) {
    _timer.stop();
  }
  _timer.setInterval(interval->value());
  _delay=delay->value();
  QDir d(dir->text());
  if(d!=_dir) {
    _dir=d;
    _loadedCount=0;
    _fileMap.clear();
  }
  // Get files currently being generated if there are
  _startTime=QDateTime::currentDateTime().addSecs(-_delay);
  _timer.start();
  showStatus();
  checkForNewFiles();
}

void DirectoryMonitor::on_stopButton_clicked()
{
  TRACE;
  _timer.stop();
  showStatus();
}

void DirectoryMonitor::checkForNewFiles()
{
  TRACE;
  QFileInfo dirInfo(_dir.path());
  /*printf("checkForNewFiles: dirmod %s check %s current %s\n",
       dirInfo.lastModified().toString("hh:mm:ss.zzz").toLatin1().data(),
       _lastCheckTime.toString("hh:mm:ss.zzz").toLatin1().data(),
       QDateTime::currentDateTime().toString("hh:mm:ss.zzz").toLatin1().data());*/
  QDateTime m=dirInfo.lastModified();
  if(m>_lastCheckTime) {
    // Modification is more than delay seconds long
    if(m<QDateTime::currentDateTime().addSecs(-_delay)) {
      _dir.refresh();
      QStringList currentFileList=_dir.entryList();
      for(QStringList::iterator it=currentFileList.begin(); it!=currentFileList.end(); ++it) {
        const QString& fileName=*it;
        if(!fileName.isEmpty() && fileName[0]=='.') continue;
        QString filePath=_dir.absoluteFilePath(fileName);
        QMap<QString, SignalFile *>::iterator itmap=_fileMap.find(filePath);
        QFileInfo fi(filePath);
        if(fi.lastModified()>_startTime) {
          if(itmap==_fileMap.end() || itmap.value()==0) {
            SubSignalPool subPool=_db->load(filePath);
            if(subPool.isEmpty()) {
              _fileMap.insert(filePath,0);
            } else {
              _fileMap.insert(filePath, subPool.first()->file());
              GeopsyCoreEngine::instance()->newSignalViewer(subPool);
              _loadedCount++;
            }
          }
        } else {
          _fileMap.insert(filePath,0);
        }
      }
      _lastCheckTime=dirInfo.lastModified();
      showStatus();
    }
  }
}


} // namespace GeopsyGui
