// =============================================================== //
//                                                                 //
//   File      : arbdbpp.cxx                                       //
//   Purpose   :                                                   //
//                                                                 //
//   Institute of Microbiology (Technical University Munich)       //
//   http://www.arb-home.de/                                       //
//                                                                 //
// =============================================================== //

#include "gb_local.h"

void GB_transaction::init(GBDATA *gb_main, bool initial) {
    ta_main = gb_main;
    ta_open = false;
    ta_err  = NULp;
#if defined(ASSERTION_USED)
    checked_for_error = 0;
#endif

    if (ta_main) {
        ta_err = initial ? GB_begin_transaction(ta_main) : GB_push_transaction(ta_main);
        if (!ta_err) {
            ta_open = true;
        }
    }
    else {
        ta_err = "NULp-Transaction";
    }
}

ARB_ERROR GB_transaction::close(ARB_ERROR& error) {
    return close(error.deliver());
}
GB_ERROR GB_transaction::close(GB_ERROR error) {
    // abort transaction if error is set

    if (error) {
        if (ta_err) {
            ta_err = GBS_global_string("%s\n(previous error: %s)", error, ta_err);
        }
        else {
            ta_err = error;
        }
    }

    // @@@ check for exported error here (when GB_export_error gets redesigned)

    if (ta_open) {
        ta_err  = GB_end_transaction(ta_main, ta_err);
        ta_open = false;
    }

    CFE(2);

    return ta_err;
}

GB_transaction::~GB_transaction() {
#if defined(ASSERTION_USED)
    GB_ERROR error;
    if (ta_open) {
        LocallyModify<int> keep_checked_for_error(checked_for_error, checked_for_error);
        error = close(NULp);
    }
    else {
        error = ta_err;
    }

    if (error) {
        fprintf(stderr, "Error while closing transaction (checked_for_error=%i): %s\n", checked_for_error, error);
        if (!checked_for_error) {
            gb_assert(0); // you need to manually use TA.close() or check TA.ok() after opening TA
        }
    }
#else // !ASSERTION_USED
    if (ta_open) {
        close(NULp);
    }
#endif
}

