# -*- coding: utf-8 -*-

import re
import json
import time
import urlparse
import requests
import pickle
import sys
import urllib
import resolveurl as urlresolver
import xbmc
import xbmcgui
import xbmcaddon
import xbmcplugin
from bs4 import BeautifulSoup
from urlparse import parse_qsl
from datetime import date, datetime
import resources.lib.meczreplay

parser = resources.lib.meczreplay.webParser()

YOUR_API_KEY = "AIzaSyBaBjcr1jYE5Eoqni-xpWwGYv3XkfgSNFE"
BLOG_ID = "7403402541563312508"

headers = {
    'Accept-Encoding': 'gzip, deflate',
    'Accept-Language': 'en-US',
    'X-Requested-With': 'blogger.com',
    'Connection': 'keep-alive',
    'Accept': 'application/json, text/plain, */*',
    'User-Agent': 'Mozilla/5.0 (Linux; U; Android 8.0.0; Nexus 5X Build/OPP3.170518.006) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/39.0.0.0 Safari/537.36 EmbeddedBrowser TVPSportMobileApp'
}

base_url = sys.argv[0]
addon_handle = int(sys.argv[1])
params = dict(parse_qsl(sys.argv[2][1:]))
addon = xbmcaddon.Addon(id='plugin.video.meczreplay')
resources = xbmc.translatePath(addon.getAddonInfo('path') + '/resources/')

_addon = xbmcaddon.Addon()
_icon = _addon.getAddonInfo('icon')


def build_url(query):
    return base_url + '?' + urllib.urlencode(query)


def build_page_url(BLOG_ID, YOUR_API_KEY, pageToken):
    pageCount = '6'
    if pageToken == "":
        return "https://www.googleapis.com/blogger/v3/blogs/" + BLOG_ID + "/posts?key=" + YOUR_API_KEY + '&maxResults=' + pageCount
    else:
        return "https://www.googleapis.com/blogger/v3/blogs/" + BLOG_ID + "/posts?key=" + YOUR_API_KEY + "&pageToken=" + pageToken + '&maxResults=' + pageCount


def get_item(BLOG_ID, YOUR_API_KEY, pageToken):
    links = []

    streams = requests.get(build_page_url(BLOG_ID, YOUR_API_KEY, pageToken),
                           headers=headers,
                           verify=False
                           ).json()
    if 'nextPageToken' in streams:
        nextPageToken = streams["nextPageToken"]
    else:
        nextPageToken = ""

    items = streams['items']
    for item in items:
        soup = BeautifulSoup(item["content"], "html.parser")
        title = str(soup.strong).replace(
            '</strong>', '').replace('<strong>', '')
        image = soup.a['href']

        soup.findAll("div", {"class": "stylelistrow"})
        data = str(soup).replace('<div class=\"separator\" style=\"clear: both; text-align: center;\">',
                                 '').replace('</div>', '').replace('\n',
                                                                   '').replace('<div dir=\"ltr\" style=\"text-align: left;\" trbidi=\"on\">', '')
        table = filter(None, re.split('<br/>|<b>|</b>|<br>|\n', str(data)))

        for line in table:
            if "blogspot.com" not in line:
                try:
                    name = line.split('<a href="')[0].replace(':', '')
                    link = line.split('<a href="')[1].split('"')[0]
                    links.append({"title": title, "image": image,
                                  "name": name, "link": link})
                except:
                    pass
    return links, nextPageToken


def resolve_url(url):
    duration = 7500
    message = "Cannot Play URL"
    stream_url = urlresolver.HostedMediaFile(url=url).resolve()
    if not stream_url:
        dialog = xbmcgui.Dialog()
        dialog.notification("URL Resolver Error", message,
                            xbmcgui.NOTIFICATION_INFO, duration)
        return False
    else:
        return stream_url


def play_video(path):
    play_item = xbmcgui.ListItem(path=path)
    vid_url = play_item.getfilename()
    stream_url = resolve_url(vid_url)
    if stream_url:
        play_item.setPath(stream_url)
    xbmcplugin.setResolvedUrl(addon_handle, True, listitem=play_item)


def create_menu_item(name, mode):
    list_item = xbmcgui.ListItem(name)
    list_item.setProperty("IsPlayable", 'False')
    image = resources + 'transparent.png'
    list_item.setArt({'thumb': image, 'poster': image, 'banner': image})
    xbmcplugin.addDirectoryItem(
        handle=addon_handle,
        url=build_url({'mode': mode}),
        listitem=list_item,
        isFolder=True)


def end_menu():
    xbmcplugin.endOfDirectory(addon_handle)


def home():
    create_menu_item('Najnowsze', 'nowe')
    create_menu_item('Szukaj', 'szukaj')
    create_menu_item('Boks', 'boks')
    create_menu_item('Bundesliga', 'bundesliga')
    create_menu_item('Cafe Futbol', 'Cafe Futbol')
    create_menu_item('Ekstraklasa', 'ekstraklasa')
    create_menu_item('Ekstraklasa po godzinach', 'ekstraklasa po godzinach')
    create_menu_item('F1', 'F1')
    create_menu_item('KSW', 'ksw')
    create_menu_item('La liga', 'laliga')
    create_menu_item('Liga europy', 'liga europy')
    create_menu_item('Liga mistrzów', 'liga mistrzów')
    create_menu_item('Liga narodów', 'liga narodów')
    create_menu_item('Liga+', 'liga+')
    create_menu_item('Liga+ extra', 'liga+ extra')
    create_menu_item('Ligue 1', 'ligue1')
    create_menu_item('MMA', 'mma')
    create_menu_item('Mundial 2018', 'mundial 2018')
    create_menu_item('Piłka z góry', 'piłka z góry')
    create_menu_item('Premierleague', 'premier league')
    create_menu_item('Serie A', 'seriea')
    create_menu_item('Siatkówka', 'siatkówka')
    end_menu()

def szukaj():
    keyb = xbmc.Keyboard('', "Wyszukiwarka MeczReplay")
    keyb.doModal()
    if keyb.isConfirmed() and len(keyb.getText().strip()) > 0 :
        search = keyb.getText()
        getItems(search)
    else:
        home()


def nowe():
    data, nextPageToken = get_item(BLOG_ID, YOUR_API_KEY, "")
    for i in data:
        video_play_url = i['link']
        url = build_url({'mode': 'play', 'playlink': video_play_url})
        li = xbmcgui.ListItem(
            i['title'] + " " + i['name'], iconImage=i['image'])
        li.setProperty('IsPlayable', 'true')
        xbmcplugin.addDirectoryItem(handle=addon_handle, url=url, listitem=li)

    list_item = xbmcgui.ListItem('NASTĘPNA STRONA  >>')
    list_item.setProperty("IsPlayable", 'False')
    image = resources + 'transparent.png'
    list_item.setArt({'thumb': image, 'poster': image, 'banner': image})
    xbmcplugin.addDirectoryItem(
        handle=addon_handle,
        url=build_url({'mode': 'next_page', 'nextPageToken': nextPageToken}),
        listitem=list_item,
        isFolder=True)

    xbmcplugin.endOfDirectory(addon_handle)


def next_page():
    prevPageToken = params.get('nextPageToken', '0')
    data, nextPageToken = get_item(BLOG_ID, YOUR_API_KEY, prevPageToken)
    for i in data:
        video_play_url = i['link']
        print(video_play_url)
        url = build_url({'mode': 'play', 'playlink': video_play_url})

        li = xbmcgui.ListItem(
            i['title'] + " " + i['name'], iconImage=i['image'])
        li.setProperty('IsPlayable', 'true')
        xbmcplugin.addDirectoryItem(handle=addon_handle, url=url, listitem=li)

    if nextPageToken != '':
        list_item = xbmcgui.ListItem('NASTĘPNA STRONA  >>')
        list_item.setProperty("IsPlayable", 'False')
        image = resources + 'transparent.png'
        list_item.setArt({'thumb': image, 'poster': image, 'banner': image})
        xbmcplugin.addDirectoryItem(
            handle=addon_handle,
            url=build_url(
                {'mode': 'next_page', 'nextPageToken': nextPageToken}),
            listitem=list_item,
            isFolder=True)

    xbmcplugin.endOfDirectory(addon_handle)


def getItems(tag):
    data = parser.getData(tag)

    for i in data:
        video_play_url = i.videoLink
        url = build_url({'mode': 'play', 'playlink': video_play_url})
        li = xbmcgui.ListItem(i.name, iconImage=i.imgLink)
        li.setProperty('IsPlayable', 'true')
        xbmcplugin.addDirectoryItem(handle=addon_handle, url=url, listitem=li)

    xbmcplugin.endOfDirectory(addon_handle)


if __name__ == '__main__':
    mode = params.get('mode', None)
    if not mode:
        home()
    elif mode == 'nowe':
        nowe()
    elif mode == 'next_page':
        next_page()
    elif mode == 'szukaj':
        szukaj()
    elif mode == 'boks':
        getItems('boks')
    elif mode == 'bundesliga':
        getItems('bundesliga')
    elif mode == 'Cafe Futbol':
        getItems('Cafe Futbol')
    elif mode == 'ekstraklasa':
        getItems('ekstraklasa')
    elif mode == 'ekstraklasa po godzinach':
        getItems('ekstraklasa po godzinach')
    elif mode == 'F1':
        getItems('F1')
    elif mode == 'ksw':
        getItems('ksw')
    elif mode == 'laliga':
        getItems('laliga')
    elif mode == 'liga europy':
        getItems('liga europy')
    elif mode == 'liga mistrzów':
        getItems('liga mistrzów')
    elif mode == 'liga narodów':
        getItems('liga narodów')
    elif mode == 'liga+':
        getItems('liga+')
    elif mode == 'liga+ extra':
        getItems('liga+ extra')
    elif mode == 'ligue1':
        getItems('ligue1')
    elif mode == 'mma':
        getItems('mma')
    elif mode == 'mundial 2018':
        getItems('mundial 2018')
    elif mode == 'piłka z góry':
        getItems('piłka z góry')
    elif mode == 'premier league':
        getItems('premier league')
    elif mode == 'seriea':
        getItems('seriea')
    elif mode == 'siatkówka':
        getItems('siatkówka')
    elif mode == 'f1':
        getItems('f1')
    elif mode == 'play':
        play_video(params['playlink'])
