#include "documentationmodel.h"

#include <QMimeData>
#include <QUrl>
#include <QFile>
#include <QtCore/qiodevice.h>
#include <QtCore/qbytearray.h>
#include <qt5/QtCore/qjsondocument.h>
#include <qt5/QtCore/qjsonobject.h>
#include <QDebug>
#include "AppInfo.h"
#include "DocumentationProject.h"

DocumentationModel::DocumentationModel(DocumentationProject* project, QObject *parent)
    : docs(project), QFileSystemModel(parent)
    {}

DocumentationModel::~DocumentationModel() {}

bool DocumentationModel::dropMimeData(const QMimeData *data
                                   , Qt::DropAction action
                                   ,int row
                                   , int column
                                   , const QModelIndex &parent) {

    bool success = QFileSystemModel::dropMimeData(data, action, row, column, parent);

    if (success){
        QString pathTo = filePath(parent) + QDir::separator();
        QString pathOld = data->urls().begin()->toLocalFile();
        QString pathNew = pathTo + QFileInfo(pathOld).fileName();

        emit fileMoved(pathNew, pathOld);
    }

    return true;
}

int
DocumentationModel::columnCount(const QModelIndex &parent) const
{
    return (parent.column() > 0) ? 0 : 5;
}

QVariant
DocumentationModel::headerData(int section, Qt::Orientation orientation, int role) const{
    if (section == 4){
        return "Title";
    }

    return QFileSystemModel::headerData(section, orientation, role);
}

Qt::ItemFlags
DocumentationModel::flags(const QModelIndex &index) const {
    auto flags = QFileSystemModel::flags(index);

    if (index.column() == 4) {
        return flags | Qt::ItemIsEditable;
    }

    return flags;
}

QVariant
DocumentationModel::data(const QModelIndex &index, int role) const
{
    if (role ==  Qt::DisplayRole || role == Qt::EditRole)
    if (index.column() == 4) {
        QString filepath = filePath(index);
        QString title = docs->getTitle(filepath);
        if (!title.isEmpty()) qDebug() << "File " << filepath <<" title is " << title;
        return docs->getTitle(filepath);
    }

    return QFileSystemModel::data(index, role);
}

bool
DocumentationModel::setData(const QModelIndex &idx, const QVariant &value, int role){
    if (idx.column() == 4) {
        QString newTitle = value.toString();
        QString filepath = filePath(idx);

        docs->project.insert(filepath, QJsonObject({{"title", QJsonValue(newTitle)}}));

//        auto i = project.object().find(filepath);
//        if (i == project.object().end()){
//
//
//
//
//        } else {
////            QJsonObject record = i.value().toObject();
////            record.insert("title", QJsonValue(newTitle));
//
//
//
//            i.value() = QJsonObject({{"title", QJsonValue(newTitle)}});
//        }


//            QJsonObject projectObj = project.object();
//            auto j = projectObj.find(filepath);
//
//            if (j != projectObj.end()){
//                qDebug() << QJsonDocument(j.value().toObject()).toJson(QJsonDocument::Indented);
//            }

        qDebug()  << "set title: `" << newTitle <<"` for file: `" << filepath << "'";
        return true;
    }

    return QFileSystemModel::setData(idx, value, role);
}

//QString
//DocumentationModel::filePath(QModelIndex i) const{
//    return reinterpret_cast<QFileSystemModel*>(sourceModel())->filePath(this->mapToSource(i));
//}

//bool
//DocumentationModel::lessThan(const QModelIndex &left, const QModelIndex &right) const {
//    return filePath(left) < filePath(right);
//            auto i = project.find(filepath);
//
//            if (i == project.end()){
//                return "";
//            }
//
//            return (i.value().toObject()["title"].toString());
//}

//void QSortFilterProxyModelPrivate::sort()
//{
//    Q_Q(QSortFilterProxyModel);
//    emit q->layoutAboutToBeChanged(QList<QPersistentModelIndex>(), QAbstractItemModel::VerticalSortHint);
//    QModelIndexPairList source_indexes = store_persistent_indexes();
//    IndexMap::const_iterator it = source_index_mapping.constBegin();
//    for (; it != source_index_mapping.constEnd(); ++it) {
//        QModelIndex source_parent = it.key();
//        Mapping *m = it.value();
//        sort_source_rows(m->source_rows, source_parent);
//        build_source_to_proxy_mapping(m->source_rows, m->proxy_rows);
//    }
//    update_persistent_indexes(source_indexes);
//    emit q->layoutChanged(QList<QPersistentModelIndex>(), QAbstractItemModel::VerticalSortHint);
//}