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

__all__ = ('TelephoneF',)

import re

from ..uio import _s

from .strings import UnicodeF

class TelephoneF(UnicodeF):
    RE_PREFIX = re.compile(r'^00262')

    def parse(self, s):
        s = UnicodeF.parse(self, s)
        if s is None: return None

        t = self.RE_SPACES.sub(u'', s)
        t = t.replace(u"+", "00")
        t = self.RE_PREFIX.sub(u"0", t)
        mo = self.RE_ONLY_NUMBERS.match(t)
        if mo is None:
            raise ValueError("Invalid telephone: %s" % s)

        if len(t) == 6: t = u'0262' + t
        return t

    def format(self, t):
        if t is None: return u""
        elif len(t) == 10:
            return u"%s %s %s %s" % (t[0:4], t[4:6], t[6:8], t[8:10])
        else:
            parts = []
            while len(t) > 3:
                parts.insert(0, t[-2:])
                t = t[:-2]
            parts.insert(0, t)
            return u" ".join(parts)
