/***************************** 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 <QAction>
#include <QDebug>
#include <QFile>
#include <QHeaderView>
#include <QLabel>
#include <QHBoxLayout>
#include <QMenu>
#include <QSlider>
#include <QSpinBox>
#include <QSplitter>
#include <QTextBrowser>
#include <QToolButton>
#include <QTreeView>
#include <QVBoxLayout>

#include "MvQContentsModel.h"
#include "MvQContentsWidget.h"

#include "Presentable.h"

MvQContentsWidget::MvQContentsWidget(QWidget* parent) :
    QWidget(parent)
{
    QVBoxLayout* layout = new QVBoxLayout;
    setLayout(layout);

    //Create layer model and view
    view_ = new QTreeView(this);
    view_->setItemDelegate(new MvQContentsDelegate());
    view_->setIndentation(10);
    //view_->setRootIsDecorated(false);
    view_->setContextMenuPolicy(Qt::CustomContextMenu);
    view_->setProperty("mvStyle", 2);

    connect(view_, SIGNAL(customContextMenuRequested(const QPoint&)),
            this, SLOT(slotShowContextMenu(const QPoint&)));

    actions_["edit"]   = new QAction(tr("Edit"), view_);
    actions_["remove"] = new QAction(tr("Remove"), view_);
    actions_["save"]   = new QAction(tr("Save"), view_);

    layout->addWidget(view_);

    model_ = new MvQContentsModel;
    view_->setModel(model_);


    //view_->setRootIsDecorated(false);

    //view_->setDragEnabled(true);
    //view_->setAcceptDrops(true);
    //view_->setDropIndicatorShown(true);
    //view_->setDragDropMode(QAbstractItemView::DragDrop);

    tree_ = 0;
}


MvQContentsWidget::~MvQContentsWidget()
{
    if (model_)
        delete model_;
    if (tree_)
        delete tree_;
}


void MvQContentsWidget::dataIsAboutToChange()
{
    model_->dataIsAboutToChange();
}

void MvQContentsWidget::reset(Presentable* /*root*/)
{
    //model_->dataIsAboutToChange();

    if (tree_) {
        delete tree_;
        tree_ = 0;
    }

    tree_ = new MvQContentsTree;

    model_->setRootNode(tree_->root());

    view_->expandAll();
}

void MvQContentsWidget::slotShowContextMenu(const QPoint& pt)
{
    //QList<QAction *> actions;

    if (!view_->indexAt(pt).isValid()) {
        //actions.append(m_addAction);
        return;
    }
    if (actions_.size() > 0)
        QMenu::exec(actions_.values(), view_->mapToGlobal(pt));
}