//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      GUI/View/Fit/FitSessionManager.cpp
//! @brief     Implements class FitSessionManager.
//!
//! @homepage  http://www.bornagainproject.org
//! @license   GNU General Public License v3 or higher (see COPYING)
//! @copyright Forschungszentrum Jülich GmbH 2018
//! @authors   Scientific Computing Group at MLZ (see CITATION, AUTHORS)
//
//  ************************************************************************************************

#include "GUI/View/Fit/FitSessionManager.h"
#include "Base/Util/Assert.h"
#include "GUI/Model/Job/JobItem.h"
#include "GUI/View/Fit/FitSessionController.h"

FitSessionManager::FitSessionManager(QObject* parent)
    : QObject(parent)
    , m_active_controller(nullptr)
{
}

FitSessionManager::~FitSessionManager()
{
    for (auto* jobItem : m_item_to_controller.keys())
        disconnect(jobItem, nullptr, this, nullptr);
}

FitSessionController* FitSessionManager::sessionController(JobItem* jobItem)
{
    FitSessionController* result(nullptr);

    auto it = m_item_to_controller.find(jobItem);
    if (it == m_item_to_controller.end()) {
        result = createController(jobItem);
        m_item_to_controller.insert(jobItem, result);
    } else {
        result = it.value();
    }

    m_active_controller = result;

    return result;
}

FitSessionController* FitSessionManager::createController(JobItem* jobItem)
{
    connect(jobItem, &QObject::destroyed, this, &FitSessionManager::removeController,
            Qt::UniqueConnection);

    auto* result = new FitSessionController(this);
    result->setJobItem(jobItem);
    return result;
}

//! Removes manager for given jobItem

void FitSessionManager::removeController(QObject* destroyed_obj)
{
    auto it = m_item_to_controller.find((JobItem*)destroyed_obj);
    ASSERT(it != m_item_to_controller.end());
    if (m_active_controller == it.value())
        m_active_controller = nullptr;
    delete it.value();
    m_item_to_controller.erase(it);
}
