# -*- coding: utf-8 -*-
# ------------------------------------------------------------
# smytvshow
# Gui wrapper to xbmc
# http://smystero.dlinkddns.org/smytvwhow/
# ------------------------------------------------------------

import xbmcgui
import xbmc

import plugin

from core import items
from player import traktPlayer
import logger
import config

'''
VideoViewId
=========================
'''

#Lista
CommonRootView = 50

#Lista Grande
FullWidthList = 51

#Icone
ThumbnailView = 500

#Poster
PosterWrapView = 501

#Fanart
PosterWrapView2_Fanart = 508

#Info media
MediaListView3  = 503

#Info media 2
MediaListView2 = 504

#Info media 3
MediaListView4 = 515

#Largo
WideIconView = 505

MusicVideoInfoListView = 511

AddonInfoListView1 = 550

AddonInfoThumbView1 = 551

LiveTVView1 = 560

lv_types = (50, 51, 500, 501, 508, 503, 504, 515, 505)

def_view_main = lv_types[int(config.get_setting("def_view_main"))]
def_view_pushers = lv_types[int(config.get_setting("def_view_pushers"))]
def_view_favorites = lv_types[int(config.get_setting("def_view_favorites"))]
def_view_pusher_main = lv_types[int(config.get_setting("def_view_pusher_main"))]
def_view_categories = lv_types[int(config.get_setting("def_view_categories"))]
def_view_series = lv_types[int(config.get_setting("def_view_series"))]
def_view_seasons = lv_types[int(config.get_setting("def_view_seasons"))]
def_view_episodes = lv_types[int(config.get_setting("def_view_episodes"))]
def_view_last = lv_types[int(config.get_setting("def_view_last"))]
def_view_videos = lv_types[int(config.get_setting("def_view_videos"))]


def render_items(item_list=None, view_id=None, upd=False):
    succeeded = True
    if item_list is not None:
        for item in item_list:
            if isinstance(item, items.BaseItem):
                li = xbmcgui.ListItem(label=item.title, label2=item.title)
                decorate_list_item(li, item)
                if not item.folder:
                    '''
                    VERY IMPORTANT!!!!!
                     ONLY IF THE ITEM IS PLAYABLE WE MUST SET THIS PROPERTY TO TRUE
                     OTHERWISE NO MATTER WHAT ISPLAYABLE SAYS, XBMC CONSIDER IT
                     AS PLAYABLE
                    '''
                    if item.playable:
                        li.setProperty('IsPlayable', str(item.playable))

                plugin.add_directory_item(li, item.build_url(), item.folder)
    plugin.end_of_directory(succeeded, upd)

    if view_id is not None:
        setForcedView(view_id)

    return


def get_user_input(full_title):
    text = ""
    keyboard = xbmc.Keyboard(full_title)
    keyboard.doModal()
    ok = keyboard.isConfirmed()
    if ok:
        text = keyboard.getText()
    return ok, text


def show_select_dialog(title, options):
    dia = xbmcgui.Dialog()
    choice = dia.select(title, options)
    return choice


def error_dialog(message):
    dlg = xbmcgui.Dialog()
    head = config.get_localized_string(30912)
    dlg.ok(head, message)
    return


def progress_dialog(dlg, message, percentage=0):
    if dlg is None:
        dlg = xbmcgui.DialogProgress()
        dlg.create(config.get_name(), message)
    else:
        dlg.update(percentage, message)
        if percentage >= 100:
            dlg.close()
    return dlg

def progress_dialogBG(dlg, message, percentage=0):
    if dlg is None:
        dlg = xbmcgui.DialogProgressBG()
        dlg.create(config.get_name(), message)
    else:
        dlg.update(percent=percentage, message=message)
        if percentage >= 100:
            dlg.close()
    return dlg


def yes_no_dialog(title, message):
    dlg = xbmcgui.Dialog()
    return dlg.yesno(title, message)


def play_media(item=None):
    if item is not None:
        if isinstance(item, items.MediaItem):

            playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
            playlist.clear()

            li = xbmcgui.ListItem(label=item.title, label2=item.title)
            decorate_list_item(li, item)
            playlist.add(item.media_url, li)

            # Play it!
            player_type = xbmc.PLAYER_CORE_AUTO
            player = traktPlayer(player_type)
            player.play(playlist)


def decorate_list_item(li, item):
    if isinstance(item, items.TestMediaItem):
        li.setArt(
            dict(thumb=item.thumbnail, poster=item.thumbnail, banner=item.banner,
                 fanart=item.fanart))

        infolabels = dict(
            #path="http://download.wavetlan.com/SVV/Media/HTTP/H264/Other_Media/"H264_test7_voiceclip_mp4_480x360.mp4",
            #duration="60",
            votes="100",
            rating=7.5,
            overlay=7,
            playcount=10)

        li.setInfo('video', infolabels)
    else:
        if isinstance(item, items.MenuItem):
            #li.setIconImage("DefaultGenre.png")
            li.setArt(
                dict(thumb=item.thumbnail, poster=item.thumbnail, banner=item.banner,
                     fanart=item.fanart))
            #if not item.thumbnail == "":
                #li.setThumbnailImage(item.thumbnail)

    if isinstance(item, items.MediaItem):
        infolabels = dict(
            genre=item.properties["genre"],
            year=item.properties["year"],
            episode=item.properties["episode"],
            season=item.properties["season"],
            rating=item.properties["rating"],
            director=item.properties["director"],
            cast=item.properties["cast"],
            castandrole=item.properties["castandrole"],
            mpaa=item.properties["mpaa"],
            plot=item.properties["plot"],
            plotoutline=item.properties["plotoutline"],
            duration=item.properties["duration"],
            tvshowtitle=item.properties["tvshowtitle"],
            writer=item.properties["writer"],
            title=item.properties["title"],
            premiered=item.properties["premiered"],
            status=item.properties["status"],
            code=item.properties["code"],
            votes=item.properties["votes"],
            dateadded=item.properties["dateadded"],
            overlay=item.properties["overlay"],
            playcount=item.properties["playcount"],
            path=item.properties["path"])

        li.setArt(
            dict(thumb=item.properties["poster"], poster=item.properties["poster"], banner=item.properties["banner"],
                 fanart=item.properties["fanart"]))

        if item.show_id != 0:
            temp_title = "%02d.%s" % (item.properties["episode"], item.properties["title"])
            temp_title = "%s - %s" % (temp_title, item.properties["server"])
            temp_title = "%s - %s" % (temp_title, item.properties["quality"])
            temp_title = config.get_localized_string(30903) % temp_title
        else:
            temp_title = "%s - %s" % (item.properties["title"], item.properties["server"])
            temp_title = "%s - %s" % (temp_title, item.properties["quality"])
            temp_title = "%s" % temp_title


        li.setLabel(temp_title)
        li.setLabel2(item.properties["title"])
        li.setInfo('video', infolabels)
    else:
        if isinstance(item, items.ServerItem):
            infolabels = dict(
                genre=item.properties["genre"],
                year=item.properties["year"],
                episode=item.properties["episode"],
                season=item.properties["season"],
                rating=item.properties["rating"],
                director=item.properties["director"],
                cast=item.properties["cast"],
                mpaa=item.properties["mpaa"],
                plot=item.properties["plot"],
                plotoutline=item.properties["plotoutline"],
                duration=item.properties["duration"],
                tvshowtitle=item.properties["tvshowtitle"],
                writer=item.properties["writer"],
                title=item.properties["title"],
                premiered=item.properties["premiered"],
                status=item.properties["status"],
                code=item.properties["code"],
                votes=item.properties["votes"],
                dateadded=item.properties["dateadded"],
                overlay=item.properties["overlay"],
                playcount=item.properties["playcount"])

            li.setArt(
                dict(thumb=item.properties["poster"], poster=item.properties["poster"], banner=item.properties["banner"],
                     fanart=item.properties["fanart"]))

            if item.show_id != 0:
                temp_title = ""
                if item.from_search:
                    temp_title = "  "
                temp_title = temp_title  + "%02d.%s" % (item.properties["episode"], item.properties["title"])
                temp_title = "%s - %s" % (temp_title, item.properties["server"])
                temp_title = config.get_localized_string(30903) % temp_title
            else:
                temp_title = "%s - %s" % (item.properties["title"], item.properties["server"])
                temp_title = "%s" % temp_title

            li.setLabel(temp_title)
            li.setLabel2(item.properties["title"])
            li.setInfo('video', infolabels)
        else:
            if isinstance(item, items.EpisodeItem):
                infolabels = dict(
                    genre=item.properties["genre"],
                    year=item.properties["year"],
                    episode=item.properties["episode"],
                    season=item.properties["season"],
                    rating=item.properties["rating"],
                    director=item.properties["director"],
                    cast=item.properties["cast"],
                    castandrole=item.properties["castandrole"],
                    mpaa=item.properties["mpaa"],
                    plot=item.properties["plot"],
                    plotoutline=item.properties["plotoutline"],
                    duration=item.properties["duration"],
                    tvshowtitle=item.properties["tvshowtitle"],
                    writer=item.properties["writer"],
                    title=item.properties["title"],
                    premiered=item.properties["premiered"],
                    status=item.properties["status"],
                    code=item.properties["code"],
                    votes=item.properties["votes"],
                    dateadded=item.properties["dateadded"],
                    overlay=item.properties["overlay"],
                    playcount=item.properties["playcount"])

                li.setArt(
                    dict(thumb=item.properties["poster"], poster=item.properties["poster"],
                         banner=item.properties["banner"],
                         fanart=item.properties["fanart"]))
                if item.show_id != 0:
                    temp_title = config.get_localized_string(30903) % (
                    "%02d.%s" % (item.properties["episode"], item.properties["title"]))
                else:
                    temp_title = '%s' % item.properties["title"]

                li.setLabel(temp_title)
                li.setLabel2(item.properties["title"])
                li.setInfo('video', infolabels)
            else:
                if isinstance(item, items.SeasonItem):
                    infolabels = dict(
                        genre=item.properties["genre"],
                        year=item.properties["year"],
                        season=item.properties["season"],
                        rating=item.properties["rating"],
                        cast=item.properties["cast"],
                        castandrole=item.properties["castandrole"],
                        mpaa=item.properties["mpaa"],
                        plot=item.properties["plot"],
                        plotoutline=item.properties["plotoutline"],
                        duration=item.properties["duration"],
                        tvshowtitle=item.properties["tvshowtitle"],
                        title=item.properties["title"],
                        premiered=item.properties["premiered"],
                        status=item.properties["status"],
                        code=item.properties["code"],
                        votes=item.properties["votes"],
                        dateadded=item.properties["dateadded"])

                    li.setArt(
                        dict(thumb=item.properties["poster"], poster=item.properties["poster"],
                             banner=item.properties["banner"],
                             fanart=item.properties["fanart"]))

                    temp_title = item.properties["title"]
                    if item.show_id != 0:
                        if item.properties["subbed"] == 1:
                            temp_title = "%s (%s)" % (temp_title, config.get_localized_string(30904))
                        temp_title = config.get_localized_string(30903) % temp_title
                    else:
                        if item.properties["subbed"] == 1:
                            temp_title = "%s (%s)" % (temp_title, config.get_localized_string(30904))
                        temp_title = '%s' % temp_title

                    li.setLabel(temp_title)
                    li.setLabel2(temp_title)
                    li.setInfo('video', infolabels)
                else:
                    if isinstance(item, items.ShowItem):
                        infolabels = dict(
                            genre=item.properties["genre"],
                            year=item.properties["year"],
                            rating=item.properties["rating"],
                            cast=item.properties["cast"],
                            castandrole=item.properties["castandrole"],
                            mpaa=item.properties["mpaa"],
                            plot=item.properties["plot"],
                            plotoutline=item.properties["plotoutline"],
                            duration=item.properties["duration"],
                            tvshowtitle=item.properties["tvshowtitle"],
                            title=item.properties["title"],
                            premiered=item.properties["premiered"],
                            status=item.properties["status"],
                            code=item.properties["code"],
                            votes=item.properties["votes"],
                            dateadded=item.properties["dateadded"])
                        li.setInfo('video', infolabels)
                        li.setArt(
                            dict(thumb=item.properties["poster"], poster=item.properties["poster"],
                                 banner=item.properties["banner"],
                                 fanart=item.properties["fanart"]))
                        if item.show_id != 0:
                            temp_title = config.get_localized_string(30903) % item.properties["title"]
                        else:
                            temp_title = '%s' % item.properties["title"]

                        li.setLabel(temp_title)
                        li.setLabel2(temp_title)

                        if item.show_id == 0:
                            contextMenuItems = []

                            run_item = \
                                items.MenuItem(None,
                                               config.get_localized_string(30910),
                                               'add_to_fav',
                                               extra={
                                                   "title": item.title,
                                                   "pusher": item.source,
                                                   "url": items.url_encode(item.extra),
                                                   "action": item.action,
                                                   "target_type": item.target_type,
                                                   "target": item.target
                                               })
                            contextMenuItem = (run_item.title, 'XBMC.RunPlugin(%s)' % (run_item.build_url()))
                            contextMenuItems.append(contextMenuItem)

                            li.addContextMenuItems(contextMenuItems)
                        else:
                            contextMenuItems = []

                            run_item = \
                                items.MenuItem(None,
                                               config.get_localized_string(30914),
                                               'rem_from_fav',
                                               extra={
                                                   "show_id": item.show_id,
                                                   "pusher": item.source
                                               })
                            contextMenuItem = (run_item.title, 'XBMC.RunPlugin(%s)' % (run_item.build_url()))
                            contextMenuItems.append(contextMenuItem)

                            li.addContextMenuItems(contextMenuItems)

    return


def refresh():
    xbmc.executebuiltin('Container.Refresh()')


def refresh_url(url):
    xbmc.executebuiltin('Container.Refresh(%s)' % url)


def update_url(url, replace = False):
    if not replace:
        xbmc.executebuiltin('Container.Update(%s)' % url)
    else:
        xbmc.executebuiltin('Container.Update(%s,%s)' % (url, 'replace'))


def run(url):
    xbmc.executebuiltin('XBMC.RunPlugin(%s)' % url)


def setForcedView(view_id):
    if config.get_setting("forced_view") == "true":
        xbmc.executebuiltin("Container.SetViewMode(%d)" % view_id)

