//
// Created by xajhuang on 2023/3/29.
//
#ifdef SQLITE_ON
#include <sqlite3.h>
#include <string.h>
#include "zlog_module.h"
#include "user_errno.h"
#include "config.h"
#include "database.h"
#include "common.h"

static sqlite3 *g_pSqlHandle = NULL;

int db_sqlite3_init() {
    int         rc;
    const char *pDbPath = cfg_get_sqlite_db_name();

    if (pDbPath == NULL || strlen(pDbPath) == 0) {
        return ERR_SUCCESS;
    }

    if (g_pSqlHandle == NULL) {
        rc = sqlite3_open_v2(pDbPath, &g_pSqlHandle, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL);

        if (rc != SQLITE_OK) {
            LOG_MOD(error,
                    ZLOG_MOD_DB,
                    "Create SQLite3 Database at %s error: %s(%d)\n",
                    pDbPath,
                    sqlite3_errstr(rc),
                    rc);
            return -ERR_DB_CONNECT;
        }
    }

    LOG_MOD(info, ZLOG_MOD_DB, "Used SQLite3 database: %s\n", pDbPath);

    return ERR_SUCCESS;
}

int db_sqlite3_get_rows(const char *pSqlCmd, char ***dbResult, int *pnRow, int *pnColumn, char **pErr) {
    if (pSqlCmd == NULL || strlen(pSqlCmd) == 0) {
        LOG_MOD(error, ZLOG_MOD_DB, "Input params pSqlCmd error\n");
        return -ERR_INPUT_PARAMS;
    }

    if (g_pSqlHandle) {
        int rc = sqlite3_get_table(g_pSqlHandle, pSqlCmd, dbResult, pnRow, pnColumn, pErr);

        if (rc != SQLITE_OK) {
            LOG_MOD(error, ZLOG_MOD_DB, "Run {%s} SQL command error:\n%s\n", pSqlCmd, sqlite3_errmsg(g_pSqlHandle));
            return -ERR_DB_SQL_EXEC;
        }

        return ERR_SUCCESS;
    } else {
        LOG_MOD(error, ZLOG_MOD_DB, "SQlite3 database uninit\n");
        return -ERR_DB_UNINIT;
    }
}

int db_sqlite3_sql_exec(const char *pSqlCmd, void *pCallback, void *pData, char **pErr) {

    if (pSqlCmd == NULL || strlen(pSqlCmd) == 0) {
        LOG_MOD(error, ZLOG_MOD_DB, "Input params pSqlCmd error\n");
        return -ERR_INPUT_PARAMS;
    }

    if (g_pSqlHandle) {
        int rc = sqlite3_exec(g_pSqlHandle, pSqlCmd, pCallback, pData, pErr);

        if (rc != SQLITE_OK) {
            LOG_MOD(error, ZLOG_MOD_DB, "Run {%s} SQL command error:\n%s\n", pSqlCmd, sqlite3_errmsg(g_pSqlHandle));
            return -ERR_DB_SQL_EXEC;
        }

        return ERR_SUCCESS;
    } else {
        LOG_MOD(error, ZLOG_MOD_DB, "SQlite3 database uninit\n");
        return -ERR_DB_UNINIT;
    }
}

void db_sqlite3_uninit() {
    if (g_pSqlHandle) {
        DEBUG_CODE_LINE();
        sqlite3_close(g_pSqlHandle);
    }
}
#endif