/***************************** 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 <QDebug>
#include <QInputDialog>
#include <QMessageBox>
#include <QToolButton>
#include <QTabBar>
#include <QStackedWidget>

#include "MvQFolderDrawerPanel.h"

#include "MvQContextMenu.h"
#include "MvQDrawerView.h"
#include "MvQFolderModel.h"

#include "Folder.h"
#include "IconClass.h"
#include "IconFactory.h"
#include "IconObject.h"

MvQFolderDrawerPanel::MvQFolderDrawerPanel(QWidget* parent) :
    MvQDrawerPanel(parent)
{
    // Init
    parentFolder_ = Folder::folder("stationary");
    if (parentFolder_) {
        parentFolder_->scan();

        const std::map<std::string, IconObjectH>& kids = parentFolder_->kids();
        for (const auto& kid : kids) {
            IconObject* obj = kid.second;
            if (kid.second->isFolder()) {
                auto* folder = static_cast<Folder*>(obj);
                createDrawer(folder);
            }
        }

        parentFolder_->addObserver(this);
    }

    // Add cornerbutton
    auto* tb = new QToolButton(this);
    tb->setIcon(QPixmap(QString::fromUtf8(":/desktop/add_drawer.svg")));
    tb->setAutoRaise(true);
    tb->setToolTip(tr("Add new drawer"));
    addCornerButton(tb);

    // Selection
    connect(tb, SIGNAL(clicked(bool)),
            this, SLOT(slotCreateDrawer(bool)));
}

MvQFolderDrawerPanel::~MvQFolderDrawerPanel()
{
    parentFolder_->removeObserver(this);
}

MvQContextItemSet* MvQFolderDrawerPanel::cmSet()
{
    static MvQContextItemSet cmItems("FolderDrawerPanel");
    return &cmItems;
}

void MvQFolderDrawerPanel::setIconPositions()
{
    /*for(int i=0; i < tab_->count(); i++)
    {
        MvQDrawerView* view  =static_cast<MvQDrawerView*>(stacked_->widget(i));
        if(view)
            view->slotSetPositions();
    }*/
}

//---------------------
//
//---------------------

void MvQFolderDrawerPanel::createDrawer(Folder* folder)
{
    auto* model = new MvQFolderModel(this);
    model->setFolder(folder);

    auto* drawer = new MvQDrawerView(model);
    MvQDrawerPanel::addDrawer(drawer, QString::fromStdString(folder->name()));
    // drawer->setHelper(true);

    connect(drawer, SIGNAL(itemEntered(IconObject*)),
            this, SIGNAL(itemEntered(IconObject*)));

    connect(drawer, SIGNAL(desktopCommandRequested(QString, QPoint)),
            this, SLOT(slotCommandFromView(QString, QPoint)));
}


//==============================================
//
// Context menu + button actions
//
//===============================================

void MvQFolderDrawerPanel::slotCreateDrawer(bool)
{
    std::string offeredName = getUniqueName("Drawer");

    bool ok;
    QString text = QInputDialog::getText(nullptr,
                                         tr("Create new drawer"),
                                         tr("Drawer name:"), QLineEdit::Normal,
                                         QString::fromStdString(offeredName), &ok);

    if (!ok || text.isEmpty())
        return;

    std::string name = text.toStdString();

    parentFolder_ = Folder::folder("stationary");
    if (!parentFolder_)
        return;

    const IconClass& kind = IconClass::find("FOLDER");
    IconFactory::create(parentFolder_, name, kind);
}

void MvQFolderDrawerPanel::renameDrawer(int index)
{
    if (index < 0 || index >= drawerCount())
        return;

    bool ok;
    QString text = QInputDialog::getText(nullptr,
                                         tr("Rename drawer"),
                                         tr("Drawer name:"), QLineEdit::Normal,
                                         drawerText(index), &ok);

    if (ok && !text.isEmpty()) {
        Folder* folder = indexToFolder(index);
        std::string name = getUniqueName(text.toStdString());
        if (folder)
            folder->rename(name);
    }
}

void MvQFolderDrawerPanel::deleteDrawer(int index)
{
    if (index < 0 || index >= drawerCount())
        return;

    if (QMessageBox::question(nullptr, tr("Delete drawer"), tr("Do you want to delete drawer") + " <b>" + drawerText(index) + "</b>?",
                              QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel) == QMessageBox::Cancel) {
        return;
    }

    Folder* folder = indexToFolder(index);
    if (folder)
        folder->toWastebasket();
}


//----------------------------------------------
// Observer methods
//----------------------------------------------

void MvQFolderDrawerPanel::arrived(IconObject* obj)
{
    auto* folder = dynamic_cast<Folder*>(obj);
    if (!folder)
        return;

    createDrawer(folder);
}

void MvQFolderDrawerPanel::renamed(IconObject* obj, const std::string&)
{
    auto* folder = dynamic_cast<Folder*>(obj);
    if (!folder)
        return;

    MvQDrawerPanel::renameDrawer(folderToIndex(folder), QString::fromStdString(folder->name()));
}

void MvQFolderDrawerPanel::gone(IconObject* obj)
{
    auto* folder = dynamic_cast<Folder*>(obj);
    if (!folder)
        return;

    int index = folderToIndex(folder);
    MvQFolderModel* model = indexToModel(index);

    MvQDrawerPanel::deleteDrawer(folderToIndex(folder));

    if (model)
        delete model;
}

//----------------------------------------------
// Context menu
//----------------------------------------------

void MvQFolderDrawerPanel::command(QString name, int index)
{
    if (name == "deleteDrawer") {
        deleteDrawer(index);
    }
    else if (name == "renameDrawer") {
        renameDrawer(index);
    }
}

// Desktop menu signal from one of the views
void MvQFolderDrawerPanel::slotCommandFromView(QString name, QPoint /*pos*/)
{
    if (name == "deleteDrawer" || name == "renameDrawer") {
        auto* view = dynamic_cast<MvQDrawerView*>(sender());
        if (!view)
            return;

        int index = drawerIndex(view);
        if (index != 0)
            command(name, index);
    }
}


std::string MvQFolderDrawerPanel::getUniqueName(const std::string& name)
{
    Folder* folder = Folder::folder("stationary");
    if (folder) {
        return folder->uniqueName(name);
    }
    return std::string(name);
}

int MvQFolderDrawerPanel::folderToIndex(Folder* f)
{
    for (int i = 0; i < drawerCount(); i++) {
        auto* view = dynamic_cast<MvQDrawerView*>(drawer(i));

        if (view->currentFolder() == f)
            return i;
    }

    return -1;
}

Folder* MvQFolderDrawerPanel::indexToFolder(int index)
{
    auto* view = dynamic_cast<MvQDrawerView*>(drawer(index));
    return (view) ? view->currentFolder() : nullptr;
}

MvQFolderModel* MvQFolderDrawerPanel::indexToModel(int index)
{
    auto* view = dynamic_cast<MvQDrawerView*>(drawer(index));
    return (view) ? view->folderModel() : nullptr;
}
