// ========================================================= //
//                                                           //
//   File      : app.cxx                                     //
//   Purpose   : code specific to arb GUI apps using DB      //
//                                                           //
//   Coded by Ralf Westram (coder@reallysoft.de) in Dec 25   //
//   http://www.arb-home.de/                                 //
//                                                           //
// ========================================================= //

#include "app.hxx"
#include <macros.hxx>
#include <aw_root.hxx>
#include <arbdbt.h>

#include <list>
#include <algorithm>

using namespace std;

static list<ArbDisconnectCallback> callbacks;

void ARB_atdisconnect_callback(const ArbDisconnectCallback& cb) {
    // Make sure the passed callback may be called multiple times.
    //
    // Callbacks added via this function are called once for each used arb database,
    // ie. they might be called multiple times, if multiple databases are opened
    // (e.g. in ARB_MERGE or when using import).
    //
    // The 'gb_main' passed to these callbacks will never be NULp, and the callback
    // will never be called multiple times with the same 'gb_main'.
    //
    // Identical callbacks are added only once.

    if (find(callbacks.begin(), callbacks.end(), cb) == callbacks.end()) {
        callbacks.push_front(cb);
    }
}

void ARB_disconnect_from_db(AW_root *aw_root, GBDATA*& gb_main_ref) {
    // disconnect arb application from database:
    //
    // - shutdown database server
    // - deny further usage of passed pointer 'gb_main_ref'
    //   (which should be the global database pointer, i.e. GLOBAL.gb_main or similar in case of the main database).
    // - unlink awars which are bound to database
    // - close the database
    //
    // After disconnecting from the main database you should exit ASAP.
    // After disconnecting from other databases, your program may continue.
    // The latter happens when using the importer.

    if (gb_main_ref) {
        shutdown_macro_recording_via_database(aw_root, gb_main_ref);

        GBCMS_shutdown(gb_main_ref); // shutdown DB server (if any)

        GBDATA *gb_main = gb_main_ref;

        arb_assert(aw_root);
        aw_root->unlink_awars_from_DB(gb_main);

        // call disconnect callbacks for passed database:
        for (list<ArbDisconnectCallback>::const_iterator cb = callbacks.begin(); cb != callbacks.end(); ++cb) {
            (*cb)(aw_root, gb_main);
        }

        gb_main_ref = NULp; // avoid further usage
        GB_close(gb_main);
    }
}

