/***************************************************************************
 *   Copyright (C) 2020 by S. MANKOWSKI / G. DE BURE support@mankowski.fr  *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program. If not, see <https://www.gnu.org/licenses/>  *
 ***************************************************************************/
/** @file
* This file implements classes SKGTransactionMng.
*
* @author Stephane MANKOWSKI / Guillaume DE BURE
*/
#include "skgtransactionmng.h"
#include "skgdocument.h"
#include "skgerror.h"

SKGTransactionMng::SKGTransactionMng(SKGDocument* iDocument,
                                     const QString& iName,
                                     SKGError* iError,
                                     int iNbStep,
                                     bool iRefreshViews)
{
    m_parentDocument = iDocument;
    m_error = iError;
    m_errorInBeginTransaction = false;
    if ((m_parentDocument != nullptr) && (m_error != nullptr)) {
        *m_error = m_parentDocument->beginTransaction(iName, iNbStep, QDateTime::currentDateTime(), iRefreshViews);
        m_errorInBeginTransaction = (m_error->isFailed());
    }
}

SKGTransactionMng::~SKGTransactionMng()
{
    if ((m_parentDocument != nullptr) && (m_error != nullptr)) {
        // close the transaction based on error
        if (!m_errorInBeginTransaction) {
            if (m_error->isSucceeded()) {
                SKGError opError = *m_error;  // In case of the message is not empty
                *m_error = m_parentDocument->endTransaction(true);
                if (m_error->isSucceeded()) {
                    *m_error = opError;
                }
            } else {
                m_parentDocument->endTransaction(false);
            }
        }
        m_parentDocument = nullptr;
        m_error = nullptr;
    }
}
