"""
$URL: svn+ssh://svn.mems-exchange.org/repos/trunk/dulcinea/lib/timestamped.py $
$Id: timestamped.py 29840 2007-05-30 16:00:09Z rmasse $
"""
from dulcinea.sort import attr_sort
from qp.lib.spec import Mixin, datetime_with_tz
from qp.pub.common import site_now

def timestamp_sorted(timestamped_sequence):
    return attr_sort(timestamped_sequence, 'timestamp')

def reverse_timestamp_sorted(timestamped_sequence):
    result = timestamp_sorted(timestamped_sequence)
    result.reverse()
    return result

class Timestamped (Mixin):

    timestamp_is = datetime_with_tz

    def __init__(self):
        self.set_timestamp()

    def get_timestamp(self):
        return self.timestamp

    def set_timestamp(self):
        self.timestamp = site_now()


def convert_datetimes_to_timezone_aware(connection, default_tzinfo=None):
    """
    This is for use in database update scripts.
    """
    from qp.lib.tz import Eastern
    import datetime as datetime_module
    old_datetime = datetime_module.datetime
    tz = default_tzinfo or Eastern
    class datetime (old_datetime):
        number_of_datetimes = 0
        default_tzinfo = tz
        def __new__(klass, *args, **kwargs):
            datetime.number_of_datetimes += 1
            self = old_datetime.__new__(old_datetime, *args, **kwargs)
            if self.tzinfo is None:
                self = self.replace(tzinfo=klass.default_tzinfo)
            assert self.__class__ is old_datetime
            return self
    datetime_module.datetime = datetime
    datetime.__module__ = 'datetime'
    previous = datetime.number_of_datetimes
    for object in connection.get_crawler():
        if datetime.number_of_datetimes > previous:
            object._p_note_change()
            previous = datetime.number_of_datetimes
    datetime_module.datetime = old_datetime
