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

__all__ = ('WeekdayF',)

from ..base import isnum
from ..uio import _s
from ..dates import isanydate, ensure_date

from .strings import UnicodeF

class WeekdayF(UnicodeF):
    LUNDI = u"lundi"
    MARDI = u"mardi"
    MERCREDI = u"mercredi"
    JEUDI = u"jeudi"
    VENDREDI = u"vendredi"
    SAMEDI = u"samedi"
    DIMANCHE = u"dimanche"

    JOURS = [j.capitalize() for j in (LUNDI, MARDI, MERCREDI, JEUDI, VENDREDI, SAMEDI, DIMANCHE)]
    JOUR_MAP = {u"0": LUNDI, u"l": LUNDI, u"lun": LUNDI,
                u"1": MARDI, u"ma": MARDI, u"mar": MARDI,
                u"2": MERCREDI, u"me": MERCREDI, u"mer": MERCREDI,
                u"3": JEUDI, u"j": JEUDI, u"jeu": JEUDI,
                u"4": VENDREDI, u"v": VENDREDI, u"ven": VENDREDI,
                u"5": SAMEDI, u"s": SAMEDI, u"sam": SAMEDI,
                u"6": DIMANCHE, u"d": DIMANCHE, u"dim": DIMANCHE,
                }

    def __parse(self, wd):
        wd = UnicodeF.parse(self, wd)
        j = self.RE_SPACES.sub(u'', wd)
        j = self.JOUR_MAP.get(j.lower(), j).capitalize()
        return j

    def __invalid(self, wd):
        return ValueError(_s(u"Jour incorrect: %s" % repr(wd)))

    def get_weekday(self, wd):
        if wd is None: return None
        elif isnum(wd): return wd % 7
        elif isanydate(wd): return ensure_date(wd).weekday()
        j = self.__parse(wd)
        try: return self.JOURS.index(j)
        except ValueError: raise self.__invalid(wd)

    def parse(self, wd):
        if wd is None: return None
        elif isnum(wd): return self.JOURS[wd % 7]
        elif isanydate(wd): return self.JOURS[ensure_date(wd).weekday()]
        j = self.__parse(wd)
        if j in self.JOURS: return j
        else: raise self.__invalid(wd)

    def format(self, j):
        if j is None: return u""
        else: return j
