/*PGR-GNU*****************************************************************
File: ordering_process.cpp

Copyright (c) 2025-2026 pgRouting developers
Mail: project@pgrouting.org

Developers:
Copyright (c) 2025-2026 pgRouting developers
Mail: bipashagayary at gmail.com
Mail: wifiblack0131 at gmail.com

------

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, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

 ********************************************************************PGR-GNU*/

#include "process/ordering_process.h"

extern "C" {
#include "c_common/postgres_connection.h"
#include "c_common/e_report.h"
#include "c_common/time_msg.h"
}

#include <string>
#include <sstream>

#include "cpp_common/report_messages.hpp"
#include "cpp_common/assert.hpp"
#include "drivers/ordering_driver.hpp"

/**
 which = 0 -> sloan
 which = 1 -> cuthillmckee
 which = 2 -> king

 This is c++ code, linked as C code, because pgr_process_foo is called from C code
 */
void pgr_process_ordering(
        const char* edges_sql,
        enum Which which,
        int64_t **result_tuples,
        size_t *result_count) {
    pgassert(edges_sql);
    pgassert(!(*result_tuples));
    pgassert(*result_count == 0);
    pgr_SPI_connect();

    std::ostringstream log;
    std::ostringstream err;
    std::ostringstream notice;

    clock_t start_t = clock();
    do_ordering(
            edges_sql? edges_sql : "",
            which,
            (*result_tuples), (*result_count),
            log, notice, err);

    switch (which) {
        case SLOAN:
            time_msg(std::string(" processing pgr_sloanOrdering").c_str(), start_t, clock());
            break;
        case CUTCHILL:
            time_msg(std::string(" processing pgr_cuthillMckeeOrdering").c_str(), start_t, clock());
            break;
        case KING:
            time_msg(std::string(" processing pgr_kingOrdering").c_str(), start_t, clock());
            break;
        case TOPOSORT:
            time_msg(std::string(" processing pgr_topologicalSort").c_str(), start_t, clock());
            break;
        default:
            break;
    }

    if (!err.str().empty() && (*result_tuples)) {
        if (*result_tuples) pfree(*result_tuples);
        (*result_tuples) = nullptr;
        (*result_count) = 0;
    }

    pgrouting::report_messages(log, notice, err);
    pgr_SPI_finish();
}
