#include "projectpresent.h"
#include "command_list.h"

#include <QInputDialog>
#include <QMenu>
#include <QVBoxLayout>

using namespace Components;
using namespace CommandList;
using namespace Schedule;
using namespace DataModel;

ProjectPresent::ProjectPresent(CommandsDispatcher *core, DocumentsManager *mgr, QWidget *parent)
    : QWidget(parent), source(core), view_present(new QTreeView(this)) {
    auto layout = new QVBoxLayout(this);

    layout->addWidget(view_present);
    view_present->setModel(mgr->projectManager()->model());
    view_present->setHeaderHidden(true);

    view_present->setContextMenuPolicy(Qt::CustomContextMenu);
    connect(view_present,   &QTreeView::customContextMenuRequested,
            this,           &ProjectPresent::menu_popup);
    connect(view_present,   &QTreeView::doubleClicked,
            this,           &ProjectPresent::open_target);
}

QModelIndex ProjectPresent::currentIndex() const { return view_present->currentIndex(); }

QString ProjectPresent::name() const
{
    return NAME(ProjectPresent);
}

QWidget *ProjectPresent::widget() const { return (QWidget *)this; }

void ProjectPresent::menu_popup(const QPoint &p)
{
    QMenu m;
    m.addAction("新建路径", [this](){
        auto path_string = QInputDialog::getText(this, "输入路径定义/packa/packb/packc", "路径定义：");
        if(path_string.isEmpty())
            return;

        source->postCommand(NewPackage(path_string));
    });

    auto index = this->view_present->currentIndex();
    if(index.isValid()){
        auto mgr = source->get<DocumentsManager>(NAME(DocumentsManager));
        auto menu = m.addMenu("新建文件");
        auto views = mgr->fileTypes();
        for (auto &it : views) {
            menu->addAction(it, [this, &it, &index, mgr]() {
                auto name = QInputDialog::getText(this, "输入文件名称", "文件名称");
                auto path = mgr->converter(index);
                source->postCommand(NewFile(path, name, it));
            });
        }

        m.addSeparator();
        m.addAction("移除节点");
    }


    m.exec(mapToGlobal(p));
}

void ProjectPresent::open_target(const QModelIndex &t)
{
    auto mgr = source->get<DocumentsManager>(NAME(DocumentsManager));
    auto path = mgr->converter(t);
    source->postCommand(OpenFile(path));
}
