
/***************************** 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 "MvQFileListModel.h"

#include <QDebug>
#include "MvQFileList.h"

MvQFileListModel::MvQFileListModel(QObject* parent) :
    QAbstractItemModel(parent)
{
}

void MvQFileListModel::setFileList(MvQFileList* data)
{
    beginResetModel();
    data_ = data;
    endResetModel();

    connect(data_, SIGNAL(fileAddRemoveBegin()),
            this, SLOT(slotDataAddRemoveBegin()));

    connect(data_, SIGNAL(fileAddRemoveEnd()),
            this, SLOT(slotDataAddRemoveEnd()));
}

int MvQFileListModel::columnCount(const QModelIndex& parent) const
{
    return (parent.isValid()) ? 0 : 1;
}

int MvQFileListModel::rowCount(const QModelIndex& parent) const
{
    if (!parent.isValid()) {
        return (data_) ? data_->count() : 0;
    }

    return 0;
}


Qt::ItemFlags MvQFileListModel::flags(const QModelIndex& /*index*/) const
{
    Qt::ItemFlags defaultFlags = Qt::ItemIsEnabled | Qt::ItemIsSelectable;
    return defaultFlags;
}

QVariant MvQFileListModel::data(const QModelIndex& index, int role) const
{
    if (!index.isValid() || !data_)
        return {};

    if (index.row() < 0 || index.row() >= data_->count())
        return {};

    if (role == Qt::DisplayRole) {
        return data_->name(index.row());
    }
    else if (role == Qt::ToolTipRole) {
        return data_->path(index.row());
    }

    return {};
}

QVariant MvQFileListModel::headerData(const int /*section*/, const Qt::Orientation /*orient*/, const int /*role*/) const
{
    return {};
}

QModelIndex MvQFileListModel::index(int row, int column, const QModelIndex& parent) const
{
    if (parent.isValid())
        return {};

    return createIndex(row, column, (void*)nullptr);
}


QModelIndex MvQFileListModel::parent(const QModelIndex& /*index*/) const
{
    return {};
}

QString MvQFileListModel::indexToPath(const QModelIndex& idx) const
{
    if (data_ && idx.row() >= 0 && idx.row() < data_->count())
        return data_->path(idx.row());

    return {};
}

QModelIndex MvQFileListModel::pathToIndex(QString f) const
{
    for (int i = 0; i < data_->count(); i++) {
        if (f == data_->path(i))
            return createIndex(i, 0);
    }
    return {};
}

void MvQFileListModel::slotDataAddRemoveBegin()
{
    endResetModel();
}


void MvQFileListModel::slotDataAddRemoveEnd()
{
    endResetModel();
}
