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

#include <QComboBox>
#include <QDebug>
#include <QFrame>
#include <QHBoxLayout>
#include <QLabel>
#include <QScrollArea>
#include <QStackedWidget>
#include <QVBoxLayout>

#include "EditorFactory.h"
#include "FamilyScanner.h"
#include "IconClass.h"
#include "IconFactory.h"
#include "IconObject.h"
//#include "Log.h"
#include "RequestPanel.h"

#include "MvQRequestPanelWidget.h"

FamilyEditor::FamilyEditor(const IconClass& name, const std::string& kind) :
    MvQEditor(name, kind),
    scanner_(FamilyScanner::find(name))
{
    auto* w = new QFrame(this);
    w->setFrameShape(QFrame::StyledPanel);

    auto* hb = new QHBoxLayout(this);
    w->setLayout(hb);

    centralLayout_->addWidget(w);
    centralLayout_->addSpacing(4);

    comboLayout_ = new QGridLayout;
    comboLayout_->setVerticalSpacing(4);
    comboLayout_->setHorizontalSpacing(4);
    comboLayout_->setContentsMargins(2, 4, 2, 4);
    hb->addLayout(comboLayout_);
    hb->addStretch(1);

    // pages
    page_ = new QStackedWidget(this);
    centralLayout_->addWidget(page_);

    Request r(name.name().c_str());
    makePages(0, r);

    // Now we have all the combos defined we cand add signals-slots.
    foreach (QComboBox* cb, combos_) {
        connect(cb, SIGNAL(currentIndexChanged(int)),
                this, SLOT(slotChangePage(int)));
    }
}

void FamilyEditor::setStartPage()
{
    if (!current_)
        return;

    std::vector<std::string> keyValues;
    const Request& r = current_->requestForVerb(class_.name());

    const std::vector<std::string>& p = scanner_.params();
    for (unsigned int i = 0; i < p.size(); i++) {
        const char* keyVal = r(p[i].c_str());
        if (keyVal) {
            QString qsv(keyVal);
            for (int j = 0; j < combos_.at(i)->count(); j++) {
                if (combos_.at(i)->itemData(j, Qt::UserRole).toString() == qsv) {
                    combos_.at(i)->setCurrentIndex(j);
                }
            }
        }
    }
}

void FamilyEditor::makePages(int n, Request& r)
{
    const std::vector<std::string>& p = scanner_.params();
    if (n >= static_cast<int>(p.size()))
        return;

    std::string paramName = p[n];

    const std::vector<std::string>& v = scanner_.values(paramName);
    const std::vector<std::string>& b = scanner_.beau(paramName);

    for (unsigned int i = 0; i < v.size(); i++) {
        r(paramName.c_str()) = v[i].c_str();

        if (combos_.count() < n + 1) {
            int row = combos_.count();
            auto* lab = new QLabel("<b>" + QString::fromStdString(paramName) + ": </b>", this);
            auto* combo = new QComboBox(this);
            comboLayout_->addWidget(lab, row, 0);
            comboLayout_->addWidget(combo, row, 1, Qt::AlignLeft);
            combos_ << combo;
        }

        QString name(b[i].c_str());

        if (combos_.at(n)->count() < static_cast<int>(v.size())) {
            QComboBox* combo = combos_.at(n);
            combo->addItem(name, QString::fromStdString(v[i]));
        }

        // Last keyword --> we create a panel
        if (n == static_cast<int>(p.size()) - 1) {
            Request s = class_.language().expand(r);
            const char* type = s(scanner_.keyword().c_str());

            if (type) {
                // Create panel
                std::vector<std::string> classes;
                classes.push_back(class_.name());

                auto* w = new MvQRequestPanelWidget(classes, this);
                auto* panel = new RequestPanel(IconClass::find(type), w, this, false, type);
                panels_.push_back(panel);

                auto* area = new QScrollArea(this);
                area->setWidgetResizable(true);
                page_->addWidget(area);
                area->setWidget(w);

                connect(w, SIGNAL(iconDropped(IconObject*)),
                        this, SLOT(slotIconDropped(IconObject*)));
            }
        }

        makePages(n + 1, r);
    }
}


IconObject* FamilyEditor::copy(const std::string& /*name*/)
{
    // IconObject* o = IconFactory::create(name, class_);
    // panel_.apply();
    // o->request(panel_.request());
    // return o;
    return nullptr;
}


void FamilyEditor::apply()
{
    if (!current_)
        return;

    Request r = current_->requestForVerb(class_.name());

    std::map<std::string, std::string> keyVals;
    keyValues(keyVals);
    for (auto& keyVal : keyVals) {
        r(keyVal.first.c_str()) = keyVal.second.c_str();
    }

    int i = page_->currentIndex();
    if (i >= 0 && i < static_cast<int>(panels_.size())) {
        panels_.at(i)->apply();
        Request pr = panels_.at(i)->request();
        r = r + panels_.at(i)->request();
        // r.print();
        objects_.at(i)->setRequest(pr);
    }

    current_->setRequest(r);
}

void FamilyEditor::edit()
{
    if (!current_)
        return;

    objects_.clear();

    for (auto& panel : panels_) {
        const IconClass& kind = panel->iconClass();

        // Create icon object
        Request panelReq = current_->requestForVerb(kind.name());

        if (!panelReq)
            panelReq = Request(kind.name());

        panelReq.print();

        IconObjectH obj = IconFactory::createTemporary(current_, panelReq, &kind);
        objects_.push_back(obj);
    }

    MvQEditor::edit();

    setStartPage();
}

void FamilyEditor::reset()
{
    for (unsigned int i = 0; i < panels_.size(); i++) {
        panels_.at(i)->reset(objects_.at(i));
    }
}

void FamilyEditor::close()
{
    for (auto& panel : panels_) {
        panel->close();
    }
    objects_.clear();
}

// Request FamilyEditor::currentRequest(long custom_expand)
//{
// panel_.apply();
// return custom_expand ? panel_.request(custom_expand) : panel_.request();
// }

void FamilyEditor::replace(IconObjectH /*o*/)
{
    // panel_.replace(o);
}

void FamilyEditor::merge(IconObjectH /*o*/)
{
    // panel_.merge(o);
}


void FamilyEditor::slotChangePage(int)
{
    // Works only for two keywords (this is the maximum currently)!!!!

    int index = 0;
    if (combos_.count() == 1) {
        index = combos_.at(0)->currentIndex();
    }
    else if (combos_.count() == 2) {
        index = combos_.at(0)->currentIndex();
        index *= combos_.at(1)->count();
        index += combos_.at(1)->currentIndex();
    }

    page_->setCurrentIndex(index);

    MvQEditor::changed();
}

void FamilyEditor::keyValues(std::map<std::string, std::string>& keyValues)
{
    const std::vector<std::string>& p = scanner_.params();
    for (unsigned int i = 0; i < p.size(); i++) {
        std::string keyVal = p[i];
        int index = combos_.at(i)->currentIndex();
        if (index > -1) {
            keyValues[keyVal] = combos_.at(i)->itemData(index, Qt::UserRole).toString().toStdString();
        }
    }
}


void FamilyEditor::slotIconDropped(IconObject* obj)
{
    merge(obj);
}


static EditorMaker<FamilyEditor> maker1("FamilyEditor");
