# -*- coding: utf-8 -*-
import re, md5
from string import lower

strip_bad_char = '\\\':"*^ _(),\t.'

# if an url is too long, first remove these words.
# warning: '-' are mandatory for the first and last words, for future '-'.join() sake.
unwanted_url_words = ['-titre', 'titre', 'livre', 'partie', 'chapitre', 'section', 'sous', 'paragraphe',
                      'reglementaire', 'legislative', 'decret', 'decrets', 'arrete', 'arretes', 'simples',
                      'annexe', 'annexes',
                      'du', 'de', 'la', 'le', 'les', 'des', 'd', 'l', 'a', 'aux', 'par', 'et',
                      'un', 'une', 'en', 'sont', 'c', 'sur',
                      '[xiv]+',
                      'premiere', '(deux|trois|quatr|cinqu|six|sept|huit)ieme',
                      'bis', '1er', 'ier-',
                      ]

strip_unwanted_url_words = re.compile(r'\d|' + '-|-'.join(unwanted_url_words) )
strip_extra_hyphens = re.compile(r'-+')

CharMapping = {
    u'\u0152': 'oe',
    u'\u0153': 'oe',
    u'\u2015': '-',
    u'\xab': '-',
    u'\xb0': 'o',
    u'\xbb': '-',
    u'\xc0': 'a',
    u'\xc2': 'a',
    u'\xc7': 'c',
    u'\xc8': 'e',
    u'\xc9': 'e',
    u'\xca': 'e',
    u'\xce': 'i',
    u'\xcf': 'i',
    u'\xd4': 'o',
    u'\xe0': 'a',
    u'\xe2': 'a',
    u'\xe7': 'c',
    u'\xe8': 'e',
    u'\xe9': 'e',
    u'\xea': 'e',
    u'\xeb': 'e',
    u'\xee': 'i',
    u'\xef': 'i',
    u'\xf4': 'o',
    u'\xf9': 'u',
    u'\xfb': 'u',
    }

def utftourl(text):
    str = ''
    for item in text:
        try:
            ascii = item.encode('ascii')
        except UnicodeError:
            ascii = CharMapping[item]
        if ascii not in strip_bad_char: 
            str += ascii
        else:
            str += '-'

    str = strip_extra_hyphens.sub('-', lower(str)).strip('-')

    if len(str) > 96:
        _str = ''
        __str = str
        while _str != __str:
            _str = __str
            __str = strip_extra_hyphens.sub('-', strip_unwanted_url_words.sub('-', _str))

        str = __str[0:min(63, len(__str))] + '-' + md5.md5(str).hexdigest()[0:7]

    return str
