"""
$URL: svn+ssh://svn.mems-exchange.org/repos/trunk/dulcinea/lib/period.py $
$Id: period.py 31138 2008-09-17 02:43:20Z dbinger $
"""
from qp.lib.spec import Specified, specify, add_getters, datetime_with_tz


class Period (Specified):

    start_is = (datetime_with_tz, None)
    end_is = (datetime_with_tz, None)

    def __init__(self, start=None, end=None):
        specify(self, start=start, end=end)

    def __contains__(self, time):
        if self.start and self.start >= time:
            return False
        if self.end and self.end <= time:
            return False
        return True

    def __nonzero__(self):
        return not (self.start and self.end and self.start >= self.end)
    __bool__ = __nonzero__

    def __eq__(self, other):
        return (isinstance(other, Period) and
                self.start == other.start and self.end == other.end)

    def __str__(self):
        return 'Period(%s, %s)' % (self.start, self.end)

    def __repr__(self):
        return self.__str__()

    def is_bounded(self):
        return self.start and self.end

    def intersection(self, period):
        def start_order(a, b):
            if a is None:
                return True
            elif b is None:
                return False
            else:
                return a <= b
        def end_order(a, b):
            if b is None:
                return True
            elif a is None:
                return False
            else:
                return a <= b
        if start_order(self.start, period.start):
            start = period.start
        else:
            start = self.start
        if end_order(self.end, period.end):
            end = self.end
        else:
            end = period.end
        return Period(start, end)


add_getters(Period)
