/***************************** LICENSE START ***********************************

 Copyright 2012 ECMWF and INPE. This software is distributed under the terms
 of the Apache License version 2.0. In applying this license, ECMWF does not
 waive the privileges and immunities granted to it by virtue of its status as
 an Intergovernmental Organization or submit itself to any jurisdiction.

 ***************************** LICENSE END *************************************/

#include "codb.h"

#include <string>

#include <math.h>
#include <ctype.h>
#include <float.h>
#include <string.h>
#include "macro.h"
#include "arith.h"
#include "MvPath.hpp"
#include "MvOdb.h"


//===========================================================================
//===========================================================================

COdb::COdb(request* s) :
    InPool(todb, s)
{
    odb_ = 0;
    r = clone_all_requests(s);

    if (r) {
        const char* path = get_value(r, "PATH", 0);
        odb_ = MvOdbFactory::make(path);
    }

    IsIcon(true);  // so that InPool won't touch the data - we control its deletion in Macro
}

COdb::COdb(const char* p, int temp) :
    InPool(todb)
{
    odb_ = 0;

    r = empty_request("ODB_DB");
    // set_value(r,"PATH","%s",p);
    set_value(r, "PATH", "%s", FullPathName(p).c_str());
    set_value(r, "TEMPORARY", "%d", temp);

    if (r) {
        const char* path = get_value(r, "PATH", 0);
        odb_ = MvOdbFactory::make(path);
    }
}

/*COdb::COdb(const char  *p,int temp) : InPool(tgeopts)
{
    odb_=0;
    r = empty_request("ODB_DB");
    //set_value(r,"PATH","%s",p);
    set_value(r,"PATH","%s",FullPathName(p).c_str());
    set_value(r,"TEMPORARY","%d",temp);
}*/


long COdb::Count()
{
    if (odb_) {
        return odb_->rowNum();
    }
    else {
        return 0;
    }
}

void COdb::load(void)
{
    if (odb_)
        return;

    if (r) {
        const char* path = get_value(r, "PATH", 0);
        odb_ = MvOdbFactory::make(path);
    }
    // else
    //   is probably a geopoints structure in memory, or with zero count!
}

void COdb::unload(void)
{
    //	if( gpts.count() > 0 || (r == nullptr))
    //	  {
    /*	    if(r == nullptr)
          {
        char* path = marstmp();
        gpts.write( path );

        r = empty_request("GEOPOINTS");
        set_value(r,"TEMPORARY","1");
        set_value(r,"PATH","%s",path);
          }

        gpts.unload();
//	  }*/

    if (odb_) {
        delete odb_;
        odb_ = 0;
    }
}

int COdb::Write(FILE* f)
{
    return CopyFile(get_value(r, "PATH", 0), f);
}


/*CGeopts::CGeopts(long count) : InPool(tgeopts)
{
    r = nullptr;
    gpts.newReservedSize (count);
}*/


/*CGeopts::CGeopts(CGeopts  *p) : InPool(tgeopts)
{
    r = nullptr;
    p->load();
    gpts = p->gpts;
}*/


COdb::~COdb()
{
    if (r) {
        const char* t = get_value(r, "TEMPORARY", 0);
        const char* p = get_value(r, "PATH", 0);
        if (t && p) {
            if (atoi(t)) {
                unlink(p);
            }
        }
    }
    // if(count) delete[] pts;
    free_all_requests(r);

    if (odb_)
        delete odb_;
}

void COdb::ToRequest(request*& s)
{
    unload();
    s = r;
}

//===========================================================================
class OdbCountFunction : public Function
{
public:
    OdbCountFunction(const char* n) :
        Function(n, 1, todb) {}
    virtual Value Execute(int arity, Value* arg);
};

Value OdbCountFunction::Execute(int, Value* arg)
{
    COdb* g;
    arg[0].GetValue(g);
    // g->load();
    return Value(g->Count());
}


//-------------------------------------------------------------------
//-------------------------------------------------------------------

class OdbValueFunction : public Function
{
    bool deprecated;
    const char* newName;

public:
    OdbValueFunction(const char* n, bool d, const char* nn = nullptr) :
        Function(n, 2, todb, tstring),
        deprecated(d),
        newName(nn)
    {
        info = "Returns a list of values from the given ODB column.";
    }
    virtual Value Execute(int arity, Value* arg);
};

Value OdbValueFunction::Execute(int, Value* arg)
{
    DeprecatedMessage(deprecated, "odb", newName);

    COdb* codb;
    arg[0].GetValue(codb);

    const char* cval;
    arg[1].GetValue(cval);
    std::string columnName(cval);

    // codb->load();

    MvAbstractOdb* odb = codb->odb();

    if (!odb)
        return Value();

    const MvOdbColumn* col = odb->loadColumn(columnName);

    if (!col)
        return Value();


    if (col->rowNum() <= 0)
        return Value();

    Content* c = 0;

    if (col->type() == MvOdbColumn::Float ||
        col->type() == MvOdbColumn::Bitfield) {
        auto* v = new CVector(col->rowNum());  // vectors can only hold numbers
        c = v;
        for (int i = 0; i < col->rowNum(); i++) {
            v->setIndexedValue(i, col->floatData().at(i));
        }
    }
    if (col->type() == MvOdbColumn::Int) {
        auto* v = new CVector(col->rowNum());  // vectors can only hold numbers
        c = v;
        for (int i = 0; i < col->rowNum(); i++) {
            v->setIndexedValue(i, col->intData().at(i));
        }
    }

    else if (col->type() == MvOdbColumn::String) {
        auto* v = new CList(col->rowNum());  // we need a list to hold strings
        c = v;
        for (int i = 0; i < col->rowNum(); i++) {
            (*v)[i] = col->stringData().at(i).c_str();
        }
    }
    else if (col->type() == MvOdbColumn::Double) {
        auto* v = new CVector(col->rowNum());  // vectors can only hold numbers
        c = v;
        for (int i = 0; i < col->rowNum(); i++) {
            v->setIndexedValue(i, col->doubleData().at(i));
        }
    }

    odb->unloadColumn(columnName);

    return Value(c);
}

//-------------------------------------------------------------------
//-------------------------------------------------------------------

class OdbColumnFunction : public Function
{
public:
    OdbColumnFunction(const char* n) :
        Function(n, 1, todb)
    {
        info = "Returns the list of columns from the given ODB.";
    }
    virtual Value Execute(int arity, Value* arg);
};

Value OdbColumnFunction::Execute(int, Value* arg)
{
    COdb* codb;
    arg[0].GetValue(codb);

    MvAbstractOdb* odb = codb->odb();
    if (!odb)
        return Value();

    int colNum = odb->columnNum();
    if (colNum <= 0)
        return Value();

    Content* c = 0;
    auto* v = new CList(colNum);
    c = v;

    for (int i = 0; i < colNum; i++) {
        (*v)[i] = odb->columns()[i]->name().c_str();
    }

    return Value(c);
}

//-------------------------------------------------------------------
//===========================================================================

static void install(Context* c)
{
    c->AddFunction(new OdbCountFunction("count"));
    c->AddFunction(new OdbValueFunction("values", false));          // new version
    c->AddFunction(new OdbValueFunction("value", true, "values"));  // deprecated version
    c->AddFunction(new OdbColumnFunction("columns"));
}

static Linkage linkage(install);
