#include "SqliteInterface.h"

#include "FileLogger.h"
#include "Directory.h"

SqliteInterface::SqliteInterface()
    : mSqliteDb(nullptr)
{

}

SqliteInterface::~SqliteInterface()
{

}

std::unique_ptr<SqliteInterface> SqliteInterface::Create()
{
    return std::make_unique<SqliteInterface>();
}

void SqliteInterface::open(Database* db)
{
    Directory::createIfNotExisting(db->getPath());

    const auto path = db->getPath().string();
    int rc = ::sqlite3_open(path.c_str(), &mSqliteDb);
    if( rc )
    {
        MLOG_ERROR("Can't open database: %s\n" << sqlite3_errmsg(mSqliteDb));
        sqlite3_close(mSqliteDb);
    }
}

static int callback(void *, int argc, char **, char **)
{
    for(int i=0; i<argc; i++)
    {
        //std::cout << "%s = %s\n" << azColName[i] << argv[i] ? argv[i] : "NULL" << std::endl;

        MLOG_ERROR("NULL");
    }
    return 0;
}

void SqliteInterface::run(const std::string& statement)
{
    MLOG_INFO("Running statement: " << statement);
    char *zErrMsg = 0;
    int rc = sqlite3_exec(mSqliteDb, statement.c_str(), callback, 0, &zErrMsg);
    if (rc != SQLITE_OK)
    {
        if (zErrMsg == nullptr)
        {
            MLOG_ERROR("Unknown sql error");
        }
        else
        {
            MLOG_ERROR("SQL error: %s\n" << zErrMsg);
        }   
        sqlite3_free(zErrMsg);
    }
}

void SqliteInterface::close()
{
    sqlite3_close(mSqliteDb);
}
