/***************************** 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 <QHBoxLayout>
#include <QMenu>
#include <QPushButton>
#include <QVBoxLayout>

#include "MvKeyProfile.h"

#include "MvQKeyManager.h"
#include "MvQPlaceMark.h"
#include "MvQPlaceMarkDialog.h"
#include "MvQPlaceMarkModel.h"
#include "MvQPlaceMarkWidget.h"
#include "MvQTreeView.h"
#include "MvQPlotView.h"

#include "MgQLayoutItem.h"
#include "MgQPlotScene.h"

#define METVIEW_MULTIPAGE


MvQPlaceMarkWidget::MvQPlaceMarkWidget(MgQPlotScene* plotScene, MvQPlotView* plotView,
                                       QWidget* parent) :
    QWidget(parent)
{
    manager_ = new MvQKeyManager(MvQKeyManager::PlaceMarkType);
    //manager->loadProfiles();

    pmTree_ = new MvQPlaceMarkTree;

    plotScene_ = plotScene;
    plotView_  = plotView;

    QVBoxLayout* layout = new QVBoxLayout;
    setLayout(layout);

    //Create layer model and view
    view_ = new QTreeView(this);
    view_->setObjectName("placeMarkTree");
    //view_->setProperty("mvStyle",0);
    //view_->setAlternatingRowColors(true);
    view_->setAllColumnsShowFocus(true);
    view_->setDragEnabled(true);
    view_->setAcceptDrops(true);
    view_->setDropIndicatorShown(true);

    //view_->setActvatedByKeyNavigation(true);

    //view_->setItemDelegate(new MvQPlaceMarkDelegate());
    layout->addWidget(view_);

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

    model_->dataIsAboutToChange();
    model_->setRootNode(pmTree_->root());

    connect(model_, SIGNAL(visibilityChanged()),
            this, SLOT(slotVisibilityChanged()));

    view_->setContextMenuPolicy(Qt::CustomContextMenu);

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

    actions_["addFolder"]    = new QAction(tr("Add folder"), view_);
    actions_["addPlaceMark"] = new QAction(tr("Add placemark"), view_);
    actions_["delete"]       = new QAction(tr("Delete"), view_);
    actions_["edit"]         = new QAction(tr("Properties"), view_);

    connect(actions_["addFolder"], SIGNAL(triggered()),
            this, SLOT(slotAddFolder()));

    connect(actions_["addPlaceMark"], SIGNAL(triggered()),
            this, SLOT(slotAddPlaceMark()));

    connect(actions_["edit"], SIGNAL(triggered()),
            this, SLOT(slotEditPlaceMark()));


    //Buttons
    QHBoxLayout* hb = new QHBoxLayout;
    layout->addLayout(hb);

    QPushButton* upPb = new QPushButton("Up");

    QPushButton* downPb = new QPushButton("Down");

    hb->addWidget(downPb);
    hb->addWidget(upPb);

    connect(upPb, SIGNAL(clicked()),
            this, SLOT(slotMoveUp()));

    connect(downPb, SIGNAL(clicked()),
            this, SLOT(slotMoveDown()));

    connect(view_, SIGNAL(clicked(const QModelIndex&)),
            this, SLOT(slotLayerSelected(const QModelIndex&)));


    char* mvhome = getenv("METVIEW_DIR_SHARE");
    if (mvhome == 0) {
    }
    else {
        systemIconPath_ = QString(mvhome);
    }

    systemIconPath_.append("/icons/placemark/");
    //defaultPixmap_=QPixmap(systemIconPath_ + "");
    defaultPixmap_ = QPixmap();

    slotAddFolder();
}


MvQPlaceMarkWidget::~MvQPlaceMarkWidget()
{
    savePlaceMarks();
    delete manager_;
}

void MvQPlaceMarkWidget::slotLayerSelected(const QModelIndex& index)
{
    if (!index.isValid()) {
        return;
    }

    //int row=index.row();

    /*for(int i=0; i <  pmTree_.count(); i++)
	{
		if(i==row)
			pmTree_[i]->setHighlighted(true);
		else			
			pmTree_[i]->setHighlighted(false);

	}*/
}

void MvQPlaceMarkWidget::slotMoveUp()
{
}

void MvQPlaceMarkWidget::slotMoveDown()
{
}


void MvQPlaceMarkWidget::slotAddPlaceMark()
{
#ifndef METVIEW_MULTIPAGE
    MgQLayoutItem* layout = plotScene_->projectorItem();
#else
    MgQLayoutItem* layout = 0;
#endif

    QRectF rect = layout->mapRectToScene(layout->boundingRect());
    createPlaceMark(rect.center());


    /*MvQPlaceMark *pm=new MvQPlaceMark(plotScene_,plotView_,0);
	pm->setParentItem(0);
	pm->setData(0,QVariant("PlaceMark"));
	pm->setZValue(1.8);
	//pm->setFlags(QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsSelectable);
	pm->setActivated(true);
	pm->setName("Budapest");
	//pm->setLat(47.12);
	//pm->setLon(19.2);
	
	plotScene_->addItem(pm);
	
	pmTree_.push_back(pm);

	model_->setPlaceMarks(pmTree_);

	connect(pm,SIGNAL(itemUpdated()),
		model_,SLOT(slotItemUpdated()));*/
}
void MvQPlaceMarkWidget::slotAddFolder()
{
    MvQPlaceMarkNode* node = model_->nodeFromIndex(view_->currentIndex());
    if (!node)
        node = pmTree_->root();

    model_->dataIsAboutToChange();

    MvQPlaceMarkNode* pm = new MvQPlaceMarkNode(MvQPlaceMarkNode::FolderType);
    pm->setName("Folder");

    node->addChild(pm);
    model_->setRootNode(pmTree_->root());
}

MvQPlaceMarkItem* MvQPlaceMarkWidget::createPlaceMark(QPointF sPos)
{
    //QPointF sPos=plotView_->mapToScene(pos);
    MgQLayoutItem* layout = plotScene_->projectorItem(sPos);

    if (layout) {
        model_->dataIsAboutToChange();

        MvQPlaceMarkNode* pm = new MvQPlaceMarkNode();
        pm->setName("Untitled");
        pm->setPixmap(defaultPixmap_);

        pmTree_->root()->addChild(pm);

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

        MvQPlaceMarkItem* item = new MvQPlaceMarkItem(pm, plotScene_, plotView_, 0);
        item->setParentItem(0);
        item->setZValue(1.8);
        item->setActivated(true);
        item->setScenePosition(sPos);


        connect(item, SIGNAL(itemUpdated()),
                model_, SLOT(slotItemUpdated()));

        plotScene_->addItem(item);

        pmItems_ << item;

        return item;
    }

    return 0;
}

void MvQPlaceMarkWidget::slotEditPlaceMark()
{
    MvQPlaceMarkNode* node = model_->nodeFromIndex(view_->currentIndex());
    if (!node)
        node = pmTree_->root();

    //The dialog will set the node!!!
    MvQPlaceMarkDialog dialog(node, systemIconPath_);
    if (dialog.exec() == QDialog::Accepted) {
        //We update the model (this will will update the view)
        model_->updateItem(view_->currentIndex());
    }

    //We reset the corresponding item
    if (node->type() == MvQPlaceMarkNode::ItemType) {
        foreach (MvQPlaceMarkItem* item, pmItems_) {
            if (item->placeMark() == node)
                item->reset();
        }
    }
}

void MvQPlaceMarkWidget::savePlaceMarks()
{
    /*MvKeyProfile *prof=new MvKeyProfile("Default");

	foreach(MvQPlaceMark *pm,pmTree_)
	{
		MvKey *key=new MvKey("name","shortname");
		key->setMetaData("name",pm->name().toStdString());
		key->setMetaData("xCoord",QString::number(pm->coordinates().x()).toStdString());
		key->setMetaData("yCoord",QString::number(pm->coordinates().y()).toStdString());
		key->setMetaData("visible",(pm->isVisible())?"true":"false");
		key->setMetaData("pixmap","1");
		prof->addKey(key);
		
	}

	manager_->addProfile(prof);
	manager_->saveProfiles();*/
}


void MvQPlaceMarkWidget::slotShowTreeContextMenu(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));
}

void MvQPlaceMarkWidget::slotVisibilityChanged()
{
    foreach (MvQPlaceMarkItem* item, pmItems_) {
        item->updateVisibility();
    }
}

void MvQPlaceMarkWidget::prepareForReset()
{
}

void MvQPlaceMarkWidget::reset()
{
    foreach (MvQPlaceMarkItem* item, pmItems_) {
        item->reset();
    }
    model_->dataIsAboutToChange();
    model_->setRootNode(pmTree_->root());
}
