#include "util/simpleobject/AgDate.h"
#include "util/simpleobject/AgString.h"
#include <boost/scoped_ptr.hpp>
#include "util/TimeHelper.h"

AgDate::AgDate()
{
    time_ = boost::posix_time::microsec_clock::universal_time();
}

AgDate::AgDate(int64_t millis)
{
    time_ = boost::posix_time::from_time_t(millis / 1000) + boost::posix_time::millisec(millis % 1000);
}

AgDate::AgDate(boost::posix_time::ptime &t)
{
    time_ =  t;
}

boost::posix_time::ptime AgDate::getValue()
{
    return time_;
}

void AgDate::setValue(boost::posix_time::ptime time)
{
    this->time_ = time;
}

int64_t AgDate::toTime()
{
    boost::posix_time::time_duration dur = time_ - boost::posix_time::ptime(boost::gregorian::date(1970,1,1));

    return dur.total_milliseconds();
}

AgDate AgDate::currentDateTime()
{
    boost::posix_time::ptime t = boost::posix_time::microsec_clock::universal_time();
    return AgDate(t);
}

Cloneable *AgDate::clone()
{
    return new AgDate(time_);
}

int AgDate::compareTo(Comparable *obj)
{
    AgDate *other = static_cast<AgDate *>(obj);
    if (time_ == other->time_)
        return 0;
    else if (time_ < other->time_)
        return -1;
    else
        return 1;
}

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

int AgDate::hashCode()
{
    assert(0);
    return 0;
}

bool AgDate::equals(AgObject *obj)
{
    if (obj == NULL)
        return false;

    if (obj == this)
        return true;

    AgDate *other = dynamic_cast<AgDate *>(obj);
    if (!other)
    {
        return false;
    }

    return time_ == other->time_;
}

AgString AgDate::toString()
{
    return AgString(toTimestampString());
}

std::string AgDate::toTimestampString()
{
    return TimeHelper::getInstance().convertTimestampToString(time_);
}
