#include "datatable/field/BooleanFieldFormat.h"
#include "util/simpleobject/AgBoolean.h"
#include "util/Util.h"
#include "GlobalVars.h"

BooleanFieldFormat::BooleanFieldFormat(const AgString &name) : FieldFormat(name)
{

}

char BooleanFieldFormat::getType()
{
    return AGG_GLOBAL.BOOLEAN_FIELD;
}

std::string BooleanFieldFormat::getFieldClass()
{
    return typeid(bool).name();
}

std::string BooleanFieldFormat::getFieldWrappedClass()
{
    return typeid(bool).name();
}

AgObjectPtr BooleanFieldFormat::getNotNullDefault()
{
    return AgObjectPtr(new AgBoolean(false));
}

AgObjectPtr BooleanFieldFormat::valueFromString(const AgString &value, ClassicEncodingSettingsPtr settings, bool validate)
{
    UNUSED(settings);
    UNUSED(validate);
    if (value == AgString("1") || value == AgString("true"))
    {
        return AgObjectPtr(new AgBoolean(true));
    }
    else
    {
        return AgObjectPtr(new AgBoolean(false));
    }
}

AgString BooleanFieldFormat::valueToString(AgObjectPtr value, ClassicEncodingSettingsPtr settings)
{
    UNUSED(settings);
    AgBoolean *b = dynamic_cast<AgBoolean *>(value.get());
    assert(b);
    if (b->getValue())
        return "1";
    else
        return "0";
}

AgObjectPtr BooleanFieldFormat::convertValue(AgObjectPtr value)
{
    if (value.get() == NULL)
        return value;

    AgBoolean *b = dynamic_cast<AgBoolean *>(value.get());
    if (b)
    {
        AgObjectPtr newValue = AgObjectPtr(new AgBoolean(Util::convertToBoolean(value, true, false)));
        return newValue;
    }
    return value;
}
