//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      GUI/Model/Project/AutosaveController.cpp
//! @brief     Implements class AutosaveController.
//!
//! @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/Model/Project/AutosaveController.h"
#include "GUI/Model/Project/ProjectDocument.h"
#include "GUI/Model/Project/ProjectUtil.h"
#include "GUI/Model/Type/UpdateTimer.h"
#include <QDir>

AutosaveController::AutosaveController(QObject* parent, int update_interval_msec)
    : QObject(parent)
    , m_document(nullptr)
    , m_timer(new UpdateTimer(update_interval_msec, this))
{
    connect(m_timer, &UpdateTimer::timeToUpdate, this, &AutosaveController::onTimerTimeout);
}

void AutosaveController::setDocument(ProjectDocument* document)
{
    if (document == m_document)
        return;

    m_timer->reset();

    m_document = document;

    if (m_document) {
        connect(m_document, &QObject::destroyed, this, &AutosaveController::onDocumentDestroyed,
                Qt::UniqueConnection);
        connect(m_document, &ProjectDocument::modifiedStateChanged, this,
                &AutosaveController::onDocumentModified, Qt::UniqueConnection);
    }

    onDocumentModified();
}

void AutosaveController::setAutosaveTime(int timerInterval)
{
    m_timer->reset();
    m_timer->setTimerInterval(timerInterval);
}

//! Returns the name of autosave directory.

QString AutosaveController::autosaveDir() const
{
    if (m_document && m_document->hasValidNameAndPath())
        return GUI::Util::Project::autosaveDir(m_document->projectFullPath());

    return "";
}

QString AutosaveController::autosaveFullPath() const
{
    if (m_document && m_document->hasValidNameAndPath())
        return GUI::Util::Project::autosaveFullPath(m_document->projectFullPath());

    return "";
}

void AutosaveController::removeAutosaveDir() const
{
    if (autosaveDir().isEmpty())
        return;

    QDir dir(autosaveDir());
    dir.removeRecursively();
}

void AutosaveController::onTimerTimeout()
{
    if (m_document->isModified())
        autosave();
}

void AutosaveController::onDocumentDestroyed(QObject* object)
{
    Q_UNUSED(object);
    m_timer->reset();
    m_document = nullptr;
}

void AutosaveController::onDocumentModified()
{
    if (!m_document)
        return;

    if (m_document->isModified() && m_document->hasValidNameAndPath())
        m_timer->scheduleUpdate();
}

bool AutosaveController::assureAutoSaveDirExists() const
{
    if (m_document && m_document->hasValidNameAndPath()) {
        const QDir projectDir = m_document->projectDir();
        if (projectDir.exists() && !projectDir.exists(GUI::Util::Project::autosaveSubdir()))
            projectDir.mkdir(GUI::Util::Project::autosaveSubdir());

        return QDir(autosaveDir()).exists();
    }

    return false;
}

void AutosaveController::autosave()
{
    if (!autosaveFullPath().isEmpty() && assureAutoSaveDirExists())
        m_document->saveProjectFileWithData(autosaveFullPath());
}
