/*-----------------------------------------------------------------------------------------------*/
/* tasks_sqlconsole.cpp                                                                          */
/* copyright (c) innovaphone 2022                                                                */
/*                                                                                               */
/*-----------------------------------------------------------------------------------------------*/

#include <platform.h>
#include "sdk/common/interface/database.h"
#include "sdk/common/interface/task.h"
#include "sdk/common/interface/time.h"
#include "common/ilib/json.h"
#include "../lib/tasks_sqlconsole.h"

TaskSqlConsoleExec::TaskSqlConsoleExec(IDatabase * database, const char * query)
{
    this->database = database;
    this->query = _strdup(query);

    dataset = 0;
    total = 0;
}

TaskSqlConsoleExec::~TaskSqlConsoleExec()
{

}

void TaskSqlConsoleExec::Start(class UTask * user)
{
    start = ITime::TimeStampMilliseconds();
    database->ExecSQL(this, 0, "%q", query);
}

void TaskSqlConsoleExec::DatabaseExecSQLResult(IDatabase * const database, class IDataSet * dataset)
{
    this->dataset = dataset;
    total += ITime::TimeStampMilliseconds() - start;
    if (dataset->Eot()) {
        Complete();
        delete dataset;
    }
    else {
        Progress(0);
    }
}

void TaskSqlConsoleExec::Json(class json_io & json, word base, char * & tmp)
{
    if (dataset) {
        word obj = json.add_object(base, "result");
        for (unsigned i = 0; i < dataset->GetColumnCount(); i++) {
            if (dataset->ColumnIsNull(i)) {
                json.add_null(obj, dataset->GetColumnName(i));
            }
            else if (dataset->ColumnIsString(i)) {
                json.add_string(obj, dataset->GetColumnName(i), dataset->GetStringValue(i));
            }
            else {
                json.add_ulong64(obj, dataset->GetColumnName(i), dataset->GetULong64Value(i), tmp);
            }
        }
    }
}

void TaskSqlConsoleExec::Next()
{
    start = ITime::TimeStampMilliseconds();
    dataset->FetchNextRow();
}

void TaskSqlConsoleExec::DatabaseError(IDatabase * const database, db_error_t error)
{
    total += ITime::TimeStampMilliseconds() - start;
    Complete();
}
