import os, re
from kmediatorrent import plugin
from kmediatorrent.scrapers import scraper
from kmediatorrent.ga import tracked
from kmediatorrent.caching import cached_route
from kmediatorrent.utils import ensure_fanart
from kmediatorrent.library import library_context

# Get addon params
BASE_URL = plugin.get_setting("base_cpb")
SCRAPPER_LABEL = plugin.get_setting("cpb_label")
SCRAPPER_PICTURE = plugin.get_setting("cpb_picture")

# Set a default picture
if SCRAPPER_PICTURE == '':
    SCRAPPER_PICTURE = "%s/_template/reloaded/_styles/_images/logo.png" % BASE_URL

HEADERS = {
    "Referer": BASE_URL,
}

SORT_DATE="trie-date"
SORT_NOM="trie-nom"
SORT_TELECHARGEMENT="trie-telechargement"
SORT_SEEDS="trie-seeds"
SORT_LEECHS="trie-leechs"
SORT_CATEGORIE="trie-categorie"

SORT_DIRECTION_ASC="-a"
SORT_DIRECTION_DESC="-d"

ACTION_SEARCH="recherche"
ACTION_FILMS="films"
ACTION_SERIES="series"

TYPE_F="films"
TYPE_S="series"
TYPE_A="All"

@scraper("%s"%str(SCRAPPER_LABEL), "%s"%str(SCRAPPER_PICTURE))
@plugin.route("/cpb")
@ensure_fanart
@tracked
def cpb_index():
    return [
		{"label": "Recherche ...", "path": plugin.url_for("cpb_search")},
		{"label": "Films", "path": plugin.url_for("cpb_listAll", cat="films", page=0)},
		{"label": "    Categories ...", "path": plugin.url_for("cpb_movie_index")},
		{"label": "Series", "path": plugin.url_for("cpb_listAll", cat="series", page=0)},
		{"label": "    Categories ...", "path": plugin.url_for("cpb_serie_index")},
		{"label": "TOP 100", "path": plugin.url_for("cpb_top", type=TYPE_A)},
		{"label": "    Series", "path": plugin.url_for("cpb_top", type=TYPE_S)},
		{"label": "    Films", "path": plugin.url_for("cpb_top", type=TYPE_F)},
		{"label": "    Films 720p", "path": plugin.url_for("cpb_top", type="720p")},
		{"label": "    Films 1080p", "path": plugin.url_for("cpb_top", type="1080p")},
		{"label": "Derniers", "path": plugin.url_for("cpb_last", type=TYPE_A)},
		{"label": "    Series", "path": plugin.url_for("cpb_last", type=TYPE_S)},
		{"label": "    Films", "path": plugin.url_for("cpb_last", type=TYPE_F)},
		{"label": "    Films 720p", "path": plugin.url_for("cpb_last", type="720p")},
		{"label": "    Films 1080p", "path": plugin.url_for("cpb_last", type="1080p")}
	]

@plugin.route("/cpb/<action>/<query>/<sort>/<page>")
@library_context
@ensure_fanart
@tracked
def cpb_page(action, query, sort, page):
    from bs4 import BeautifulSoup
    from kmediatorrent.utils import url_get

    url_adr = "%s/%s/" % (BASE_URL, action)
    url_adr = url_adr + query.replace(" ","+") + "/page-" + str(page) + "," + sort
    html_data = url_get(url_adr)

    soup = BeautifulSoup(html_data, "html5lib")
    name_nodes = soup.findAll('div', re.compile('ligne[0,1]'))

    for name_node in name_nodes:
        if name_node.find('a', href=isValid) :
            yield getItemDetails(name_node)

	# Add pagination only if needed
    if soup.find('div', id="pagination") :
        yield {
            "label": ">> Next page",
            "path": plugin.url_for("cpb_page", action=action, query=query, sort=sort, page=int(page) + 1),
            "is_playable": False
        }
		
@plugin.route("/cpb/top/<type>")
@library_context
@ensure_fanart
@tracked
def cpb_top(type):
    from bs4 import BeautifulSoup
    from kmediatorrent.utils import url_get

    url_adr = "%s/top-100.php" % BASE_URL
    if type != TYPE_A:
        url_adr = url_adr + "?filtre=%s" % type
    html_data = url_get(url_adr)

    soup = BeautifulSoup(html_data, "html5lib")
    name_nodes = soup.findAll('div', re.compile('ligne[0,1]'))

    for name_node in name_nodes:
        if name_node.find('a', href=isValid) :
            yield getItemDetails(name_node)

@plugin.route("/cpb/last/<type>")
@library_context
@ensure_fanart
@tracked
def cpb_last(type):
    from bs4 import BeautifulSoup
    from kmediatorrent.utils import url_get

    url_adr = "%s/derniers-torrents.php" % BASE_URL
    if type != TYPE_A:
        url_adr = url_adr + "?filtre=%s" % type
    html_data = url_get(url_adr)

    soup = BeautifulSoup(html_data, "html5lib")
    name_nodes = soup.findAll('div', re.compile('ligne[0,1]'))

    for name_node in name_nodes:
        if name_node.find('a', href=isValid) :
            yield getItemDetails(name_node)

@plugin.route("/cpb/movie/index")
@ensure_fanart
@tracked
def cpb_movie_index():
	return [
		{"label": "Action, Aventures", "path": plugin.url_for("cpb_page", action=ACTION_FILMS, query="action-aventures", sort=SORT_DATE + SORT_DIRECTION_DESC, page=0)},
		{"label": "Biographies", "path": plugin.url_for("cpb_page", action=ACTION_FILMS, query="biographies", sort=SORT_DATE + SORT_DIRECTION_DESC, page=0)},
		{"label": "Comedies", "path": plugin.url_for("cpb_page", action=ACTION_FILMS, query="comedies", sort=SORT_DATE + SORT_DIRECTION_DESC, page=0)},
		{"label": "Comedies dramatiques", "path": plugin.url_for("cpb_page", action=ACTION_FILMS, query="comedies-dramatiques", sort=SORT_DATE + SORT_DIRECTION_DESC, page=0)},
		{"label": "Comedies musicales", "path": plugin.url_for("cpb_page", action=ACTION_FILMS, query="comedies-musicales", sort=SORT_DATE + SORT_DIRECTION_DESC, page=0)},
		{"label": "Documentaires", "path": plugin.url_for("cpb_page", action=ACTION_FILMS, query="documentaires", sort=SORT_DATE + SORT_DIRECTION_DESC, page=0)},
		{"label": "Drames", "path": plugin.url_for("cpb_page", action=ACTION_FILMS, query="drames", sort=SORT_DATE + SORT_DIRECTION_DESC, page=0)},
		{"label": "Films d'animation", "path": plugin.url_for("cpb_page", action=ACTION_FILMS, query="films-d-animation", sort=SORT_DATE + SORT_DIRECTION_DESC, page=0)},
		{"label": "Films d'horreur-epouvante", "path": plugin.url_for("cpb_page", action=ACTION_FILMS, query="films-d-horreur-epouvante", sort=SORT_DATE + SORT_DIRECTION_DESC, page=0)},
		{"label": "Films Fantastiques", "path": plugin.url_for("cpb_page", action=ACTION_FILMS, query="films-fantastiques", sort=SORT_DATE + SORT_DIRECTION_DESC, page=0)},
		{"label": "Films historiques", "path": plugin.url_for("cpb_page", action=ACTION_FILMS, query="films-historiques", sort=SORT_DATE + SORT_DIRECTION_DESC, page=0)},
		{"label": "Policiers, Thrillers", "path": plugin.url_for("cpb_page", action=ACTION_FILMS, query="policiers-thrillers", sort=SORT_DATE + SORT_DIRECTION_DESC, page=0)},
		{"label": "Romances", "path": plugin.url_for("cpb_page", action=ACTION_FILMS, query="romances", sort=SORT_DATE + SORT_DIRECTION_DESC, page=0)},
		{"label": "Science-Fiction", "path": plugin.url_for("cpb_page", action=ACTION_FILMS, query="science-fiction", sort=SORT_DATE + SORT_DIRECTION_DESC, page=0)},
		{"label": "Spectacles", "path": plugin.url_for("cpb_page", action=ACTION_FILMS, query="spectacles", sort=SORT_DATE + SORT_DIRECTION_DESC, page=0)},
		{"label": "Westerns", "path": plugin.url_for("cpb_page", action=ACTION_FILMS, query="westerns", sort=SORT_DATE + SORT_DIRECTION_DESC, page=0)},
	]

@plugin.route("/cpb/serie/index")
@ensure_fanart
@tracked
def cpb_serie_index():
	return [
		{"label": "0, A, B", "path": plugin.url_for("cpb_page", action=ACTION_SERIES, query="0-a-b", sort=SORT_DATE + SORT_DIRECTION_DESC, page=0)},
		{"label": "C, D, E", "path": plugin.url_for("cpb_page", action=ACTION_SERIES, query="c-d-e", sort=SORT_DATE + SORT_DIRECTION_DESC, page=0)},
		{"label": "F, G, H", "path": plugin.url_for("cpb_page", action=ACTION_SERIES, query="f-g-h", sort=SORT_DATE + SORT_DIRECTION_DESC, page=0)},
		{"label": "I, J, K", "path": plugin.url_for("cpb_page", action=ACTION_SERIES, query="i-j-k", sort=SORT_DATE + SORT_DIRECTION_DESC, page=0)},
		{"label": "L, M, N", "path": plugin.url_for("cpb_page", action=ACTION_SERIES, query="l-m-n", sort=SORT_DATE + SORT_DIRECTION_DESC, page=0)},
		{"label": "O, P, Q", "path": plugin.url_for("cpb_page", action=ACTION_SERIES, query="o-p-q", sort=SORT_DATE + SORT_DIRECTION_DESC, page=0)},
		{"label": "R, S, T", "path": plugin.url_for("cpb_page", action=ACTION_SERIES, query="r-s-t", sort=SORT_DATE + SORT_DIRECTION_DESC, page=0)},
		{"label": "U, V, W", "path": plugin.url_for("cpb_page", action=ACTION_SERIES, query="u-v-w", sort=SORT_DATE + SORT_DIRECTION_DESC, page=0)},
		{"label": "X, Y, Z", "path": plugin.url_for("cpb_page", action=ACTION_SERIES, query="x-y-z", sort=SORT_DATE + SORT_DIRECTION_DESC, page=0)},
	]

@plugin.route("/cpb/all/<cat>/<page>")
@ensure_fanart
@tracked
def cpb_listAll(cat, page):
    from bs4 import BeautifulSoup
    from kmediatorrent.utils import url_get

    url_adr = "%s/view_cat.php?categorie=%s&page=%s" % (BASE_URL, cat, page) #view_cat.php?categorie=films&page=1
    html_data = url_get(url_adr)

    soup = BeautifulSoup(html_data, "html5lib")
    name_nodes = soup.findAll('div', re.compile('ligne[0,1]'))

    for name_node in name_nodes:
        if name_node.find('a', href=isValid) :
            yield getItemDetails(name_node)

    if soup.find('div', id="pagination"):
        yield {
            "label": ">> Next page",
            "path": plugin.url_for("cpb_listAll", cat=cat, page=int(page) + 1),
            "is_playable": False
        }

# Analyze the health of the torrent to set a color on its returned label
def getColor(seed, leech):
	iSeed = int(seed)
	iLeech = int(leech)
	color = ""
	
	# Base sur l'algo de PopcornTime : https://github.com/popcorn-official/popcorn-app/commit/1eceaf510da6bad6b51803c7dcc7868ad096a0af
	# First calculate the Seed/Leech ratio
	if iLeech > 0:
		ratio = iSeed / iLeech
	else:
		ratio = iSeed
	# Normalize the data. Convert each to a percentage
	# Ratio: Anything above a ratio of 5 is good
	normalizedRatio = min(ratio / 5 * 100, 100)
	# Seeds: Anything above 30 seeds is good
	normalizedSeeds = min(iSeed / 30 * 100, 100)
	# Weight the above metrics differently
	# Ratio is weighted 60% whilst seeders is 40%
	weightedRatio = normalizedRatio * 0.6
	weightedSeeds = normalizedSeeds * 0.4
	weightedTotal = weightedRatio + weightedSeeds
	# Scale from [0, 100] to [0, 3]. Drops the decimal places
	scaledTotal = round((weightedTotal * 3) / 100)
	
	if scaledTotal < 1:
		color = "red"
	elif scaledTotal < 2:
		color = "orange"
	else:
		color = "green"
	return color

# Parse an item result to fill the media data
def getItemDetails(node):
	title = node.find("a").text
	tds = node.parent.findAll("td")
	seed = node.find("div","up").text
	leech = node.find("div","down").text
	color = getColor(seed, leech)
	title = title + " [COLOR %s][S:%s|L:%s][/COLOR]" %(color, seed, leech)
	html_uri = node.find("a")["href"]
	torrent_basename = os.path.basename(html_uri)
	uri_addr = BASE_URL + "/telechargement/" + torrent_basename.replace(".html",".torrent")
	img_addr = BASE_URL + "/_pictures/" + torrent_basename.replace(".html",".jpg")
	return {
		"label": title,
		"path": plugin.url_for("play", uri=uri_addr),
		"is_playable": True,
		"thumbnail" : img_addr
	}

# Check if link is for Movie or TVShow only (exclude games, musics, ebooks, etc...)
def isValid(link):
    return str(link).find('/films/') + str(link).find('/series/') > -2
	
@plugin.route("/cpb/search")
@tracked
def cpb_search():
    query = plugin.request.args_dict.pop("query", None)
    if not query:
        query = plugin.keyboard("", "KMediaTorrent - CPasBien - Recherche")
    if query:
        plugin.redirect(plugin.url_for("cpb_page", action=ACTION_SEARCH, query=query, sort=SORT_DATE + SORT_DIRECTION_DESC, page=0, **plugin.request.args_dict))