# -*- coding: utf-8 -*-
# ------------------------------------------------------------
# smytvshow
# Useful helper
# http://smystero.dlinkddns.org/smytvwhow/
# ------------------------------------------------------------

import re
import time
from xbmcutils import logger

ordinal = []
ordinal.extend(["pilot", "prima", "seconda", "terza", "quarta", "quinta", "sesta", "settima", "ottava", "nona"])
ordinal.extend(["decima", "undicesima", "dodicesima", "tredicesima", "quattordicesima", "quindicesima", "sedicesima",
                "diciassetesima", "diciottesima", "diciannovesima"])
ordinal.extend(["ventesima", "ventunesima", "ventiduesima", "ventitreesima", "ventiquattresima", "venticinquesima",
                "ventiseiesima", "ventisettesima", "ventottesima", "ventinovesima"])
ordinal.extend(["trentesima", "trentunesima", "trentaduesima", "trentatreesima", "trentaquattresima",
                "trentacinquesima", "trentaseiesima", "trentasettesima", "trentottesima", "trentanovesima"])
ordinal.extend(["quarantesima", "quarantunesima", "quarantaduesima", "quarantatreesima", "quarantaquattresima",
                "quarantacinquesima", "quarantaseiesima", "quarantasettesima", "quarantottesima", "quarantanovesima"])
ordinal.extend(["cinquantesima", "cinquantunesima", "cinquantaduesima", "cinquantatreesima", "cinquantaquattresima",
                "cinquantacinquesima", "cinquantaseiesima", "cinquantasettesima", "cinquantottesima", "cinquantanovesima"])
ordinal.extend(["sessantesima", "sessantunesima", "sessantaduesima", "sessantatreesima", "sessantaquattresima",
                "sessantacinquesima", "sessantaseiesima", "sessantasettesima", "sessantottesima", "sessantanovesima"])
ordinal.extend(["settantesima", "settantunesima", "settantaduesima", "settantatreesima", "settantaquattresima",
                "settantacinquesima", "settantaseiesima", "settantasettesima", "settantottesima", "settantanovesima"])
ordinal.extend(["ottantesima", "ottantunesima", "ottantaduesima", "ottantatreesima", "ottantaquattresima",
                "ottantacinquesima", "ottantaseiesima", "ottantasettesima", "ottantottesima", "ottantanovesima"])
ordinal.extend(["novantesima", "novantunesima", "novantaduesima", "novantatreesima", "novantaquattresima",
                "novantacinquesima", "novantaseiesima", "novantasettesima", "novantottesima", "novantanovesima"])

def is_int(s):
    try:
        int(s)
        return True
    except ValueError:
        return False


def pipe_split(s, char=' / '):
    ret = ""
    if s is not None:
        patron = '\|([^\|]+)'
        genres = re.compile(patron, re.DOTALL).findall(s)
        sep = ""
        for genre in genres:
            ret += sep + genre
            sep = char
    return ret


def get_match(data, patron, index=0):
    matches = re.findall(patron, data, flags=re.DOTALL)
    return matches[index]


def find_single_match(data, patron, index=0):
    try:
        matches = re.findall(patron, data, flags=re.DOTALL)
        return matches[index]
    except:
        return ""


def get_sha1(text):
    ret = ""
    try:
        import hashlib
        ret = hashlib.sha1(text).hexdigest()
    except:
        import sha
        import binascii
        ret = binascii.hexlify(sha.new(text).digest())

    return ret


def unescape_entity(text):
    return unescape(text)


def unescape(text):
    """Removes HTML or XML character references
       and entities from a text string.
       keep &amp;, &gt;, &lt; in the source code.
    from Fredrik Lundh
    http://effbot.org/zone/re-sub.htm#unescape-html
    """

    def fix_up(m):
        text = m.group(0)
        if text[:2] == "&#":
            # character reference
            try:
                if text[:3] == "&#x":
                    return unichr(int(text[3:-1], 16)).encode("utf-8")
                else:
                    return unichr(int(text[2:-1])).encode("utf-8")

            except ValueError:
                pass
        else:
            # named entity
            try:
                import htmlentitydefs

                text = unichr(htmlentitydefs.name2codepoint[text[1:-1]]).encode("utf-8")
            except KeyError:
                pass
            except:
                pass
        return text  # leave as is

    return re.sub("&#?\w+;", fix_up, text)


def decode_html_entities(string):
    string = fix_entities(string)
    entity_re = re.compile("&(#?)(\d{1,5}|\w{1,8});")

    def substitute_entity(match):
        from htmlentitydefs import name2codepoint as n2cp

        ent = match.group(2)
        if match.group(1) == "#":
            return unichr(int(ent)).encode('utf-8')
        else:
            cp = n2cp.get(ent)

            if cp:
                return unichr(cp).encode('utf-8')
            else:
                return match.group()

    return entity_re.subn(substitute_entity, string)[0]


def fix_entities(string):
    string = string.replace("&aacute", "&aacute;")
    string = string.replace("&eacute", "&eacute;")
    string = string.replace("&iacute", "&iacute;")
    string = string.replace("&oacute", "&oacute;")
    string = string.replace("&uacute", "&uacute;")
    string = string.replace("&Aacute", "&Aacute;")
    string = string.replace("&Eacute", "&Eacute;")
    string = string.replace("&Iacute", "&Iacute;")
    string = string.replace("&Oacute", "&Oacute;")
    string = string.replace("&Uacute", "&Uacute;")
    string = string.replace("&uuml", "&uuml;")
    string = string.replace("&Uuml", "&Uuml;")
    string = string.replace("&ntilde", "&ntilde;")
    string = string.replace("&#191", "&#191;")
    string = string.replace("&#161", "&#161;")
    string = string.replace(";;", ";")
    return string


def html_clean(text):
    text = text.replace("<center>", "")
    text = text.replace("</center>", "")
    text = text.replace("<cite>", "")
    text = text.replace("</cite>", "")
    text = text.replace("<em>", "")
    text = text.replace("</em>", "")
    text = text.replace("<b>", "")
    text = text.replace("</b>", "")
    text = text.replace("<u>", "")
    text = text.replace("</u>", "")
    text = text.replace("<li>", "")
    text = text.replace("</li>", "")
    text = text.replace("<tbody>", "")
    text = text.replace("</tbody>", "")
    text = text.replace("<tr>", "")
    text = text.replace("</tr>", "")
    text = text.replace("<![CDATA[", "")
    text = text.replace("<Br />", "")
    text = text.replace("<BR />", "")
    text = text.replace("<Br>", "")

    text = re.compile("<script.*?</script>", re.DOTALL).sub("", text)

    text = re.compile("<option[^>]*>", re.DOTALL).sub("", text)
    text = text.replace("</option>", "")

    text = re.compile("<button[^>]*>", re.DOTALL).sub("", text)
    text = text.replace("</button>", "")

    text = re.compile("<i[^>]*>", re.DOTALL).sub("", text)
    text = text.replace("</iframe>", "")
    text = text.replace("</i>", "")

    text = re.compile("<table[^>]*>", re.DOTALL).sub("", text)
    text = text.replace("</table>", "")

    text = re.compile("<td[^>]*>", re.DOTALL).sub("", text)
    text = text.replace("</td>", "")

    text = re.compile("<div[^>]*>", re.DOTALL).sub("", text)
    text = text.replace("</div>", "")

    text = re.compile("<dd[^>]*>", re.DOTALL).sub("", text)
    text = text.replace("</dd>", "")

    text = re.compile("<font[^>]*>", re.DOTALL).sub("", text)
    text = text.replace("</font>", "")

    text = re.compile("<strong[^>]*>", re.DOTALL).sub("", text)
    text = text.replace("</strong>", "")

    text = re.compile("<small[^>]*>", re.DOTALL).sub("", text)
    text = text.replace("</small>", "")

    text = re.compile("<span[^>]*>", re.DOTALL).sub("", text)
    text = text.replace("</span>", "")

    text = re.compile("<a[^>]*>", re.DOTALL).sub("", text)
    text = text.replace("</a>", "")

    text = re.compile("<p[^>]*>", re.DOTALL).sub("", text)
    text = text.replace("</p>", "")

    text = re.compile("<ul[^>]*>", re.DOTALL).sub("", text)
    text = text.replace("</ul>", "")

    text = re.compile("<h1[^>]*>", re.DOTALL).sub("", text)
    text = text.replace("</h1>", "")

    text = re.compile("<h2[^>]*>", re.DOTALL).sub("", text)
    text = text.replace("</h2>", "")

    text = re.compile("<h3[^>]*>", re.DOTALL).sub("", text)
    text = text.replace("</h3>", "")

    text = re.compile("<h4[^>]*>", re.DOTALL).sub("", text)
    text = text.replace("</h4>", "")

    text = re.compile("<!--[^-]+-->", re.DOTALL).sub("", text)

    text = re.compile("<img[^>]*>", re.DOTALL).sub("", text)

    text = re.compile("<br[^>]*>", re.DOTALL).sub("", text)

    text = re.compile("<object[^>]*>", re.DOTALL).sub("", text)
    text = text.replace("</object>", "")
    text = re.compile("<param[^>]*>", re.DOTALL).sub("", text)
    text = text.replace("</param>", "")
    text = re.compile("<embed[^>]*>", re.DOTALL).sub("", text)
    text = text.replace("</embed>", "")

    text = re.compile("<title[^>]*>", re.DOTALL).sub("", text)
    text = text.replace("</title>", "")

    text = re.compile("<link[^>]*>", re.DOTALL).sub("", text)

    text = text.replace("\t", "")
    text = unescape_entity(text)
    return text


def slugify(title):
    title = title.replace("Á", "a")
    title = title.replace("É", "e")
    title = title.replace("Í", "i")
    title = title.replace("Ó", "o")
    title = title.replace("Ú", "u")
    title = title.replace("á", "a")
    title = title.replace("é", "e")
    title = title.replace("í", "i")
    title = title.replace("ó", "o")
    title = title.replace("ú", "u")
    title = title.replace("À", "a")
    title = title.replace("È", "e")
    title = title.replace("Ì", "i")
    title = title.replace("Ò", "o")
    title = title.replace("Ù", "u")
    title = title.replace("à", "a")
    title = title.replace("è", "e")
    title = title.replace("ì", "i")
    title = title.replace("ò", "o")
    title = title.replace("ù", "u")
    title = title.replace("ç", "c")
    title = title.replace("Ç", "C")
    title = title.replace("Ñ", "n")
    title = title.replace("ñ", "n")
    title = title.replace("/", "-")
    title = title.replace("&amp;", "&")

    title = title.lower().strip()

    valid_chars = "abcdefghijklmnopqrstuvwxyz1234567890- "
    title = ''.join(c for c in title if c in valid_chars)

    title = re.compile("\s+", re.DOTALL).sub(" ", title)

    title = re.compile("\s", re.DOTALL).sub("-", title.strip())

    title = re.compile("\-+", re.DOTALL).sub("-", title)

    if title.startswith("-"):
        title = title[1:]

    if title == "":
        title = "-" + str(time.time())

    return title


def normalize(text):
    patron = '<.*?>'
    return re.sub(patron, '', text.rstrip().lstrip().replace('&#215;', 'x')\
        .replace('&#8211;', '-')\
        .replace('&#8217;', '\'')\
        .replace('&#8230;', '...')\
        .replace('&#038;', '&')\
        .replace('&hellip;', '...')\
        .replace('×', 'x')
    )
