/***************************** 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 <iostream>

#include "macro.h"

#include <stdarg.h>

Function::Function(const char* n, int arity, ...) :
    Node(n)
{
    info = 0;
    types = 0;
    cnt = arity;
    if (cnt > 0) {
        va_list list;

        types = new vtype[cnt];

        va_start(list, arity);

        for (int i = 0; i < cnt; i++)
            types[i] = va_arg(list, vtype);
        va_end(list);
    }
}

int Function::ValidArguments(int arity, Value* arg)
{
    if (cnt < 0)
        return true;
    if (arity != cnt)
        return false;
    for (int i = 0; i < arity; i++)
        if ((arg[i].GetType() & types[i]) == 0)
            return false;
    return true;
}

Value& Function::Error(const char* fmt, ...)
{
    va_list list;
    char buf[1024];
    va_start(list, fmt);
    vsprintf(buf, fmt, list);
    va_end(list);

    return Owner()->Error("%s", buf);
}

void Function::AddType(vtype t)
{
    if (cnt < 0)
        cnt = 0;
    auto* s = new vtype[cnt + 1];
    for (int i = 0; i < cnt; i++)
        s[i] = types[i];
    s[cnt++] = t;
    delete[] types;
    types = s;
}


void Function::Print(void)
{
    std::cout.setf(std::ios::left, std::ios::adjustfield);
    std::cout.width(10);
    std::cout << Name() << " : ";
    std::cout << (char*)(Info() ? Info() : "Not yet documented");
    std::cout << '\n';
}


Value Function::ToString(void)
{
    char func_string[1024];
    sprintf(func_string, "%s : %s", Name(), (char*)(Info() ? Info() : "Not yet documented"));
    return Value(func_string);
}


void Function::DeprecatedMessage(bool isDeprecated, const char* type, const char* newName)
{
    if (isDeprecated)
        marslog(LOG_WARN, "Function '%s(%s)' is deprecated (but still working); please use the equivalent '%s(%s)' instead.",
                Name(), type, newName, type);
}
