#include "datatable/field/DateFieldFormat.h"
#include "util/simpleobject/AgString.h"
#include <boost/date_time/gregorian/gregorian_types.hpp>
#include <boost/date_time/c_local_time_adjustor.hpp>
#include "IllegalArgumentException.h"
#include "GlobalVars.h"

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

}

char DateFieldFormat::getType()
{
    return AGG_GLOBAL.DATE_FIELD;
}

std::string DateFieldFormat::getFieldClass()
{
    return typeid(AgDate).name();
}

std::string DateFieldFormat::getFieldWrappedClass()
{
    return typeid(AgDate).name();
}

AgObjectPtr DateFieldFormat::getNotNullDefault()
{
    static boost::gregorian::date d(2000, boost::gregorian::Jan, 10);
    static boost::posix_time::ptime DEFAULT_DATE(d, boost::posix_time::hours(12));

    return AgObjectPtr(new AgDate(DEFAULT_DATE));
}

AgObjectPtr DateFieldFormat::valueFromString(const AgString &value, ClassicEncodingSettingsPtr settings, bool validate)
{
    UNUSED(settings);
    UNUSED(validate);
    boost::posix_time::ptime t;
    try
    {
        t = boost::posix_time::time_from_string(value.toUtf8());
    }
    catch(...)
    {
        try
        {
            int64_t millis = value.toInt64();
            return AgObjectPtr(new AgDate(millis));
        }
        catch(...)
        {
            throw IllegalArgumentException("Error parsing date from string \'" + value + "\': ");
        }

        throw IllegalArgumentException("Error parsing date from string \'" + value + "\': ");
    }

    return AgObjectPtr(new AgDate(t));
}

AgString DateFieldFormat::valueToString(AgObjectPtr value, ClassicEncodingSettingsPtr settings)
{
    UNUSED(settings);
    if (value.get() == 0)
    {
        return "";
    }
    else
    {
        return value->toString();
    }
}

std::list<AgString> DateFieldFormat::getSuitableEditors()
{
   std::list<AgString> list;
   list.push_back(AGG_GLOBAL.EDITOR_LIST);
   list.push_back(AGG_GLOBAL.EDITOR_DATE);
   list.push_back(AGG_GLOBAL.EDITOR_TIME);
   return list;
}

boost::posix_time::ptime DateFieldFormat::timestampFromString(const std::string str)
{
    boost::posix_time::ptime t = boost::posix_time::time_from_string(str);
    return t;
}

