/***************************** LICENSE START ***********************************

 Copyright 2013 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 "MvQFeatureContextMenu.h"

#include "MvRequest.h"

#include <QDebug>
#include <QAction>
#include <QLabel>
#include <QMenu>
#include <QWidgetAction>

#include "MvMiscellaneous.h"
#include "MvRequest.h"

#include "MvQFeatureCommandTarget.h"
#include "MvQMethods.h"

std::vector<MvQFeatureMenuItem*> MvQFeatureMenuItem::items_;
bool MvQFeatureMenuItem::shortcutInited_ = false;

MvQFeatureMenuItem::MvQFeatureMenuItem(bool node, QString name, QString label) :
    node_(node),
    name_(name),
    label_(label)
{
    if (!name_.isEmpty() && label_.isEmpty()) {
        label_    = name_.replace("_", " ");
        label_[0] = label_[0].toUpper();
    }
}

void MvQFeatureMenuItem::add(const MvRequest& r)
{
    const char* verb = r.getVerb();
    Q_ASSERT(verb);

    if (strcmp(verb, "item_menu") == 0 || strcmp(verb, "node_menu") == 0) {
        QString name, label;
        if (const char* ch = r("name")) {
            name = QString(ch);
        }
        if (const char* ch = r("label")) {
            label = QString(ch);
        }

        auto item = new MvQFeatureMenuItem((strcmp(verb, "node_menu") == 0), name, label);

        if (const char* ch = r("type")) {
            item->type_ = QString(ch);
        }
        if (const char* ch = r("parent")) {
            item->parent_ = QString(ch);
        }
        if (const char* ch = r("shortcut")) {
            item->shortcut_ = QString(ch);
        }

        std::vector<std::string> v;
        r.getValue("visible_for", v, true);
        for (auto s : v) {
            item->visible_for_ << QString::fromStdString(s);
        }

        r.getValue("not_visible_for", v, true);
        for (auto s : v) {
            item->not_visible_for_ << QString::fromStdString(s);
        }
        items_.push_back(item);
    }
}

QString MvQFeatureMenuItem::execute(const MvQFeatureCommandTarget& sel, QList<QAction*> extraActions, QPoint globalPos)
{
    QMenu menu;
    QMap<QString, QMenu*> subMenus;
    //if (mode != "-" && type != "-") {
    bool node = (sel.itemMode() == "node");

    QWidgetAction* labelAc = nullptr;

    if (!sel.itemType().isEmpty() && sel.itemType() != "-") {
        auto label = new QLabel(sel.itemType()[0].toUpper() + sel.itemType().mid(1));
        label->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
        label->setAlignment(Qt::AlignCenter);
        labelAc = new QWidgetAction(label);
        labelAc->setDefaultWidget(label);
        // the menu will not take ownership of the ac
        menu.addAction(labelAc);
    }

    for (auto item : items_) {
        if (item->node_ == node) {
            bool st = false;
            if (sel.itemMode() == "-") {
                st = sel.itemType() == "-" && item->type_ == "-";
            }
            else {
                st = (item->visible_for_.isEmpty() || item->visible_for_.contains(sel.itemType())) &&
                     !item->not_visible_for_.contains(sel.itemType()) && sel.isCommmandEnabled(item->name_);
            }
            if (st) {
                if (item->type_ == "sub") {
                    subMenus[item->name_] = menu.addMenu(item->label_);
                }
                else {
                    // The menus will take ownership of the action
                    QAction* ac;
                    if (!item->parent_.isEmpty() && subMenus.contains(item->parent_)) {
                        ac = subMenus[item->parent_]->addAction("");
                    }
                    else {
                        ac = menu.addAction("");
                    }
                    if (item->type_ == "separator") {
                        ac->setSeparator(true);
                    }
                    else {
                        ac->setText(item->label_);
                        ac->setData("feature:" + item->name_);
                        if (!item->shortcut_.isEmpty()) {
                            ac->setShortcut(QKeySequence(item->shortcut_));
                        }
                    }
                }
            }
        }
    }

    if (extraActions.size() > 0 && menu.actions().size() > 0) {
        auto ac = menu.addAction("");
        ac->setSeparator(true);
    }

    for (auto ac : extraActions) {
        // The menu will NOT take ownership of the action
        menu.addAction(ac);
    }

    MvQ::showShortcutInContextMenu(&menu);

    QString cmd;
    if (QAction* ac = menu.exec(globalPos, nullptr)) {
        if (!ac->isSeparator()) {
            cmd = ac->data().toString();
            if (cmd.startsWith("feature:")) {
                cmd = cmd.mid(8);
            }
            else {
                int idx = extraActions.indexOf(ac);
                if (idx >= 0) {
                    cmd = "extra:" + QString::number(idx);
                }
            }
        }
    }

    //    if (labelAc) {
    //        delete labelAc;
    //    }

    return cmd;
}

void MvQFeatureMenuItem::setupShortcut(QObject* receiver, QWidget* w, const std::string& view)
{
    if (!shortcutInited_) {
        shortcutInited_ = true;
        for (auto item : items_) {
            if (QShortcut* sc = item->createShortcut(w, view)) {
                QObject::connect(sc, SIGNAL(activated()),
                                 receiver, SLOT(slotCommandShortcut()));
            }
        }
    }
}

QShortcut* MvQFeatureMenuItem::createShortcut(QWidget* parent, const std::string& /*view*/)
{
    if (!shortcut_.isEmpty()) {
        auto* sc = new QShortcut(shortcut_, parent);
        sc->setContext(Qt::WidgetShortcut);
        sc->setProperty("id", name_);
        return sc;
    }
    return nullptr;
}

void MvQFeatureMenuItem::init()
{
    // we only load it once
    if (!items_.empty())
        return;

    std::string symFile = metview::etcDirFile("WsItems");
    if (symFile.empty())
        return;

    MvRequest r;
    r.read(symFile.c_str());
    if (r) {
        do {
            const char* verb = r.getVerb();
            Q_ASSERT(verb);
            if (strcmp(verb, "item_menu") == 0 || strcmp(verb, "node_menu") == 0) {
                MvQFeatureMenuItem::add(r);
            }
        } while (r.advance());
    }
}
