# -*- coding: utf-8 mode: python -*- vim:sw=4:sts=4:et:ai:si:sta:fenc=utf-8

__all__ = ('DateProperty', 'TimeProperty',
           )

from google.appengine.ext import db

from ulib.base.dates import pydatetime, Date, ensure_date
from ulib.base.times import Time, ensure_time

class DateProperty(db.DateProperty):
    data_type = Date

    def validate(self, value):
        if value is not None:
            value = ensure_date(value)
        return value

    def _date_to_datetime(self, date):
        return pydatetime(date.year, date.month, date.day)

    def get_value_for_datastore(self, model_instance):
        value =  self.__get__(model_instance, model_instance.__class__)
        if value is not None:
            value = self._date_to_datetime(value.date)
        return value

    def make_value_from_datastore(self, value):
        if value is None: return None
        else: return Date(value.day, value.month, value.year)

class TimeProperty(db.TimeProperty):
    data_type = Time

    def validate(self, value):
        if value is not None:
            value = ensure_time(value)
        return value

    def _time_to_datetime(self, time):
        return pydatetime(1970, 1, 1,
                          time.hour, time.minute, time.second,
                          time.microsecond)

    def get_value_for_datastore(self, model_instance):
        value =  self.__get__(model_instance, model_instance.__class__)
        if value is not None:
            value = self._time_to_datetime(value.time)
        return value

    def make_value_from_datastore(self, value):
        if value is None: return None
        else: return Time(value.hour, value.minute, value.second)
