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

__all__ = (
    'DateF', 'TimeF',
    'format_any', 'format_range',
)

from ..dates import Date, ensure_date, FR_DATEF, pydate, pydatetime
from ..times import Time, ensure_time, HM_TIMEF, pytime

from .base import Format

class DateF(Format):
    format_string = None

    def __init__(self, format_string=None):
        if format_string is None: format_string = FR_DATEF
        self.format_string = format_string

    def parse(self, s):
        if s is None: return None
        else: return ensure_date(s)

    def format(self, d):
        if d is None: return u""
        else: return d.format(self.format_string)

class TimeF(Format):
    format_string = None

    def __init__(self, format_string=None):
        if format_string is None: format_string = HM_TIMEF
        self.format_string = format_string

    def parse(self, s):
        if s is None: return None
        else: return ensure_time(s)

    def format(self, t):
        if t is None: return u""
        else: return t.format(self.format_string)

def format_date(d):
    if d is None: return u""
    else: return ensure_date(d).format()
def format_time(t):
    if t is None: return u""
    else: return ensure_time(t).format()
def format_any(dt):
    if dt is None: return u""
    if isinstance(dt, pydatetime):
        d = Date._new(dt)
        t = Time._new(dt)
        return u"%s %s" % (d.format(), t.format())
    if isinstance(dt, pydate): dt = Date._new(dt)
    elif isinstance(dt, pytime): dt = Time._new(dt)
    if isinstance(dt, Date): return dt.format()
    elif isinstance(dt, Time): return dt.format()
    return ensure_date(dt).format()

def format_range(dts, dte):
    if dts is None and dte is None: return u""
    elif dte is None: return u"%s -" % format_any(dts)
    elif dts is None: return u"- %s" % format_any(dts)
    ds, ts = format_date(dts), format_time(dts)
    de, te = format_date(dte), format_time(dte)
    if de == ds:
        if te == ts: return u"%s %s" % (ds, ts)
        else: return u"%s %s-%s" % (ds, ts, te)
    else: return u"%s %s - %s %s" % (ds, ts, de, te)
