//
// This file is part of MorphoGraphX - http://www.MorphoGraphX.org
// Copyright (C) 2012-2015 Richard S. Smith and collaborators.
//
// If you use MorphoGraphX in your work, please cite:
//   http://dx.doi.org/10.7554/eLife.05864
//
// MorphoGraphX is free software, and is licensed under under the terms of the 
// GNU General (GPL) Public License version 2.0, http://www.gnu.org/licenses.
// 
#include "FileListWidget.hpp"

#include <QDropEvent>
#include <QDragEnterEvent>
#include <QDragMoveEvent>
#include <QDragLeaveEvent>
#include <QMimeData>
#include <QUrl>
#include <QFileInfo>

#include "Information.hpp"

namespace mgx {
  FileListWidget::FileListWidget(QWidget* parent) : QListWidget(parent), handlingDrop(false)
  {
    setAcceptDrops(true);
  }
  
  void FileListWidget::dropEvent(QDropEvent* event)
  {
    handlingDrop = false;
    const QMimeData* data = event->mimeData();
    if(data->hasUrls()) {
      QStringList result;
      QList<QUrl> urls = data->urls();
      foreach(QUrl url, urls) {
        QString file = url.toLocalFile();
        result << file;
      }
      if(!result.empty()) {
        event->acceptProposedAction();
        emit filesDropped(result);
        return;
      }
    }
    QListWidget::dropEvent(event);
  }
  
  void FileListWidget::dragEnterEvent(QDragEnterEvent* event)
  {
    const QMimeData* data = event->mimeData();
    if(data->hasUrls()) {
      bool accepted = true;
      QList<QUrl> urls = data->urls();
      foreach(QUrl url, urls) {
        QString file = url.toLocalFile();
        if(file.isEmpty()) {
          accepted = false;
          break;
        }
        QFileInfo fi(file);
        if(!fi.isFile() or !fi.isReadable()) {
          accepted = false;
          break;
        }
      }
      if(accepted and (event->proposedAction() == Qt::CopyAction)) {
        handlingDrop = true;
        event->accept();
        event->acceptProposedAction();
        return;
      }
    }
    handlingDrop = false;
    QListWidget::dragEnterEvent(event);
  }
  
  void FileListWidget::dragMoveEvent(QDragMoveEvent* event)
  {
    if(!handlingDrop)
      QListWidget::dragMoveEvent(event);
    else {
      event->acceptProposedAction();
    }
  }
  
  void FileListWidget::dragLeaveEvent(QDragLeaveEvent*)
  {
    if(handlingDrop) {
      handlingDrop = false;
    }
  }
}
