/***************************** 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 <QTabWidget>
#include <QWidget>

#include "MvQTabManager.h"

MvQTabManager::MvQTabManager(QTabWidget* w) :
    tab_(w) {}


void MvQTabManager::addItem(QWidget* w, QString name, QAction* action)
{
    widget_.push_back(w);
    name_.push_back(name);
    action_.push_back(action);

    if (action) {
        connect(action, SIGNAL(toggled(bool)),
                this, SLOT(slotChangeViewStatus(bool)));
    }

    connect(tab_, SIGNAL(tabCloseRequested(int)),
            this, SLOT(slotRemoveTab(int)));
}

void MvQTabManager::setAction(int index, QAction* action)
{
    action_[index] = action;

    connect(action, SIGNAL(toggled(bool)),
            this, SLOT(slotChangeViewStatus(bool)));
}

/*QAction* MvQTabManager::action(QWidget* w)
{
    int index=widget_.indexOf(w);
    return action_[index];
}*/

void MvQTabManager::slotChangeViewStatus(bool state)
{
    QObject* obj = sender();
    auto* action = dynamic_cast<QAction*>(obj);
    int index = action_.indexOf(action);

    if (state) {
        tab_->addTab(widget_[index], tr(name_[index].toStdString().c_str()));
    }
    else {
        tab_->removeTab(tab_->indexOf(widget_[index]));
    }
}

void MvQTabManager::slotRemoveTab(int index)
{
    action_[index]->setChecked(false);
}
