import xbmc
from helper import utils
from . import common

class Playlist:
    def __init__(self, EmbyServer, SQLs):
        self.EmbyServer = EmbyServer
        self.SQLs = SQLs

    def update_SQLs(self, SQLs): # When paused, databases are closed and re-opened -> Update database
        self.SQLs = SQLs

    def change(self, Item, IncrementalSync):
        if not common.load_ExistingItem(Item, self.EmbyServer, self.SQLs["emby"], "Playlist"):
            return False

        common.set_Favorite(Item)
        common.set_Favorites_Artwork(Item, self.EmbyServer.ServerData['ServerId'])
        xbmc.log(f"EMBY.core.playlist: Process item: {Item['Name']}", 0) # DEBUG
        PlaylistItems = self.EmbyServer.API.get_Items(Item['Id'], ("Audio", "Video", "Movie", "Episode", "MusicVideo"), False, {}, "", None, True, False)
        ItemFilename = utils.valid_Filename(Item['Name'])
        M3UPlaylistAudio = ""
        M3UPlaylistVideo = ""
        KodiItemIdVideo = ""
        KodiItemIdAudio = ""

        for PlaylistItem in PlaylistItems:
            common.set_RunTimeTicks(PlaylistItem)
            common.set_streams(PlaylistItem)
            common.set_common(PlaylistItem, self.EmbyServer.ServerData['ServerId'], True, IncrementalSync)

            if PlaylistItem.get('Type', "") == "Audio":
                common.set_path_filename(PlaylistItem, self.EmbyServer.ServerData['ServerId'], None, True)
                M3UPlaylistAudio += f"#EXTINF:-1,{PlaylistItem['Name']}\n"
                M3UPlaylistAudio += f"{PlaylistItem['KodiFullPath']}\n"
            else:
                common.set_chapters(PlaylistItem, self.EmbyServer.ServerData['ServerId'])
                common.set_path_filename(PlaylistItem, self.EmbyServer.ServerData['ServerId'], None, True)
                M3UPlaylistVideo += f"#EXTINF:-1,{PlaylistItem['Name']}\n"
                M3UPlaylistVideo += f"{PlaylistItem['KodiFullPath']}\n"

        utils.delFile(f"{utils.PlaylistPathMusic}emby_{ItemFilename}_audio.m3u")
        utils.delFile(f"{utils.PlaylistPathVideo}emby_{ItemFilename}_video.m3u")

        if M3UPlaylistAudio:
            M3UPlaylistAudio = f"#EXTCPlayListM3U::M3U\n{M3UPlaylistAudio}"
            KodiItemIdAudio = f"emby_{ItemFilename}_audio"
            PlaylistPath = f"{utils.PlaylistPathMusic}{KodiItemIdAudio}.m3u"
            utils.writeFile(PlaylistPath, M3UPlaylistAudio.encode("utf-8"))

        if M3UPlaylistVideo:
            M3UPlaylistVideo = f"#EXTCPlayListM3U::M3U\n{M3UPlaylistVideo}"
            KodiItemIdVideo = f"emby_{ItemFilename}_video"
            PlaylistPath = f"{utils.PlaylistPathVideo}{KodiItemIdVideo}.m3u"
            utils.writeFile(PlaylistPath, M3UPlaylistVideo.encode("utf-8"))

        Item['KodiItemId'] = f"{KodiItemIdVideo};{KodiItemIdAudio}"
        self.SQLs["emby"].add_reference_playlist(Item['Id'], Item['LibraryId'], Item['KodiItemId'], Item['KodiArtwork']['favourite'])
        xbmc.log(f"EMBY.core.playlist: ADD/REPLACE [{Item['KodiItemId']}] {Item['Id']}", int(IncrementalSync)) # LOG
        utils.reset_querycache("Playlist")
        return False

    def remove(self, Item, IncrementalSync):
        if self.SQLs["emby"].remove_item(Item['Id'], "PlayList", Item['LibraryId']):
            self.set_favorite(False, Item)
            xbmc.log(f"EMBY.core.playlist: DELETE [{Item['KodiItemId']}] {Item['Id']}", int(IncrementalSync)) # LOG

    def userdata(self, Item, IncrementalSync, UpdateKodiFavorite):
        if UpdateKodiFavorite:
            self.set_favorite(Item['IsFavorite'], Item)

        self.SQLs["emby"].update_favourite(Item['IsFavorite'], Item['Id'], "Playlist")

        if IncrementalSync:
            utils.reset_querycache("Playlist")

        xbmc.log(f"EMBY.core.playlist: USERDATA [{Item['KodiItemId']}] {Item['Id']}", int(IncrementalSync)) # LOG
        return False

    def set_favorite(self, IsFavorite, Item):
        common.validate_FavoriteImage(Item)
        KodiItemIds = Item['KodiItemId'].split(";")

        if IsFavorite and not Item['KodiArtwork']['favourite']:
            Item['KodiArtwork']['favourite'] = self.SQLs["emby"].get_item_by_id(Item['Id'], "Playlist")[3]

        if KodiItemIds[1]: # Audio
            PlaylistName = KodiItemIds[1].replace("emby_", "").replace("_audio", "", 1).replace("_", " ")
            utils.FavoriteQueue.put(((common.set_Favorites_Artwork_Overlay("Playlist", "Audio", Item['Id'], self.EmbyServer.ServerData['ServerId'], Item['KodiArtwork']['favourite']), IsFavorite, f"plugin://plugin.service.emby-next-gen/?mode=playlist&mediatype=audio&server={self.EmbyServer.ServerData['ServerId']}&id={KodiItemIds[1]}", PlaylistName, "window", 10502),))
        else: # Video
            PlaylistName = KodiItemIds[0].replace("emby_", "").replace("_video", "", 1).replace("_", " ")
            utils.FavoriteQueue.put(((common.set_Favorites_Artwork_Overlay("Playlist", "Video", Item['Id'], self.EmbyServer.ServerData['ServerId'], Item['KodiArtwork']['favourite']), IsFavorite, f"plugin://plugin.service.emby-next-gen/?mode=playlist&mediatype=video&server={self.EmbyServer.ServerData['ServerId']}&id={KodiItemIds[0]}", PlaylistName, "window", 10025),))
