# -*- coding: utf-8 -*-
"""
The main addon module

SPDX-License-Identifier: MIT

"""
import xbmcplugin
import time
import os
import json
import re
from pathlib import Path
from .akfw import utils as pyUtils
from .akfw.kodi import Kodi
from .akfw import kodiProgressDialog as PG
from .akfw import kodiUi as KodiUI
from . import DpGronkhTv as dps


from xbmcaddon import Addon
from xbmcvfs import translatePath

class Main(Kodi):

    def __init__(self):
        super(Main, self).__init__()
        self.logger = self.createLogger('Main')

    def create_resource_path(self, *args):
        addon_path = self.getAddonPath()
        path_comps = []
        for arg in args:
            path_comps.extend(arg.split('/'))
        path = os.path.join(addon_path, 'resources', *path_comps)
        return path

    def run(self):
        mode = self.getParameters('mode')
        self.logger.info('Run Plugin with Parameters {}', self.getParameters())
        if mode == 'new':
            mmUI = KodiUI.KodiUI(self)
            self.genSubStreams(mmUI, dps.DpGronkhTv(self).getNewStreams())
        elif mode == 'random':
            mmUI = KodiUI.KodiUI(self)
            self.genSubStreams(mmUI, dps.DpGronkhTv(self).getRandomStreams())
        elif mode == 'hot':
            mmUI = KodiUI.KodiUI(self)
            self.genSubStreams(mmUI, dps.DpGronkhTv(self).getHotStreams())
        elif mode == 'all':
            mmUI = KodiUI.KodiUI(self)
            page = int(self.getParameters(pName='page', default=1))
            self.genSubAll(mmUI, dps.DpGronkhTv(self).getStreamsPaginated(page))
        elif mode == 'tags':
            mmUI = KodiUI.KodiUI(self, pContentType="")
            self.genSubTags(mmUI, dps.DpGronkhTv(self).getAllTags())
        elif mode == 'tag':
            mmUI = KodiUI.KodiUI(self)
            tagid = self.getParameters('tagid')
            self.genSubStreams(mmUI, dps.DpGronkhTv(self).getStreamByTag(tagid))
        elif mode == 'play':
            videoid = self.getParameters('videoid')
            self.logger.debug("play video with id {}", videoid)
            #
            m3u8url = dps.DpGronkhTv(self).getM3U8UrlByEpisodeId(videoid)
            self.logger.debug("m3u8 url: {}", m3u8url)
            #
            self.playItem(m3u8url)
        else:
            mmUI = KodiUI.KodiUI(self, pContentType="")
            self.genMenu(mmUI)
        

    ##########
    
    def genMenu(self, pUI):
        targetUrl = pyUtils.build_url({
                    'mode': 'new'
                })
        pUI.addDirectoryItem(
            pTitle=self.localizeString(30001),
            pUrl=targetUrl,
            pIcon=self.create_resource_path('media', 'new.png'),
            pFanart=self.create_resource_path('media', 'new.png'),
            pPlot=self.localizeString(30001)
        )
        #
        targetUrl = pyUtils.build_url({
                    'mode': 'random'
                })
        pUI.addDirectoryItem(
            pTitle=self.localizeString(30005),
            pUrl=targetUrl,
            pIcon=self.create_resource_path('media', 'most.png'),
            pFanart=self.create_resource_path('media', 'most.png'),
            pPlot=self.localizeString(30005)
        )
        #
        targetUrl = pyUtils.build_url({
                    'mode': 'hot'
                })
        pUI.addDirectoryItem(
            pTitle=self.localizeString(30002),
            pUrl=targetUrl,
            pIcon=self.create_resource_path('media', 'most.png'),
            pFanart=self.create_resource_path('media', 'most.png'),
            pPlot=self.localizeString(30002)
        )
        #
        targetUrl = pyUtils.build_url({
                    'mode': 'all'
                })
        pUI.addDirectoryItem(
            pTitle=self.localizeString(30003),
            pUrl=targetUrl,
            pIcon=self.create_resource_path('media', 'all.png'),
            pFanart=self.create_resource_path('media', 'all.png'),
            pPlot=self.localizeString(30003)
        )
        #
        targetUrl = pyUtils.build_url({
                    'mode': 'tags'
                })
        pUI.addDirectoryItem(
            pTitle=self.localizeString(30004),
            pUrl=targetUrl,
            pIcon=self.create_resource_path('media', 'tags.png'),
            pFanart=self.create_resource_path('media', 'tags.png'),
            pPlot=self.localizeString(30004)
        )
        #
        pUI.render()



    def genSubStreams(self, pUI, pData):
        uData = pyUtils.makeDictUnique(pData, "id")
        for element in uData:
            #
            self.logger.debug('genSubStreams {}', element)
            videoid = element['episode']
            targetUrl = pyUtils.build_url({
                'mode': 'play',
                'videoid': videoid,
            })
            #
            if element['title']:
                #
                title: str = element['title'].replace("⭐", "꙳")
                title = self.remove_emojis(title)
                #
                # Example Title: 'GTV1063, 2026-02-15 - RENATE, KOMM BEI, DER KOMISCHE MANN IS WIEDER IM FENNSEHN!! ⭐ Oder 247 auf @GronkhTV ⭐ !vod !pc !s'
                # It will split and use the second Part
                # parts[0]: 'GTV1063, 2026-02-15'
                # parts[1]: 'RENATE, KOMM BEI, DER KOMISCHE MANN IS WIEDER IM FENNSEHN!! ⭐ Oder 247 auf @GronkhTV ⭐ !vod !pc !s'
                if " - " in title:
                    parts = title.split(' - ', 1)
                    #
                    pattern = r"^GTV\d+, \d{4}-\d{2}-\d{2}$" # Entspricht z.B. "GTV1063, 2026-02-15"
                    #
                    if re.fullmatch(pattern, parts[0]):
                        resulttitle = parts[1].strip()
                    else:
                        resulttitle = title
                else:
                    resulttitle = title
                #
                duration = element['meta']['duration']
                #
                plot=""
                plot+="Tags: "
                #
                genres = []
                #
                for i, genre in enumerate(element['tags']):
                    genres.append(genre['title'])
                    plot+=genre['title']
                    if i != len(element['tags']) - 1:
                        plot+=", "
                #
                plot+="[CR][CR]" + self.localizeString(30011)
                #
                pUI.addListItem(
                    pTitle=resulttitle,
                    pUrl=targetUrl,
                    pDuration=duration,
                    pIcon=element['urls']['thumbnail'],
                    pAired=element['created_at'],
                    pGenres=genres,
                    pPlot=plot,
                )
        #
        pUI.render()

    def genSubAll(self, pUI, pData):
        uData = pyUtils.makeDictUnique(pData, "episode")
        for element in uData:
            #
            self.logger.info('genSubNew {}', element)
            #
            if 'title' in element and element['title']:
                #
                videoid = element['episode']
                targetUrl = pyUtils.build_url({
                    'mode': 'play',
                    'videoid': videoid,
                })
                #
                title: str = element['title'].replace("⭐", "꙳")
                title = self.remove_emojis(title)
                #
                # Example Title: 'GTV1063, 2026-02-15 - RENATE, KOMM BEI, DER KOMISCHE MANN IS WIEDER IM FENNSEHN!! ⭐ Oder 247 auf @GronkhTV ⭐ !vod !pc !s'
                # It will split and use the second Part
                # parts[0]: 'GTV1063, 2026-02-15'
                # parts[1]: 'RENATE, KOMM BEI, DER KOMISCHE MANN IS WIEDER IM FENNSEHN!! ⭐ Oder 247 auf @GronkhTV ⭐ !vod !pc !s'
                if " - " in title:
                    parts = title.split(' - ', 1)
                    #
                    pattern = r"^GTV\d+, \d{4}-\d{2}-\d{2}$" # Entspricht z.B. "GTV1063, 2026-02-15"
                    #
                    if re.fullmatch(pattern, parts[0]):
                        resulttitle = parts[1].strip()
                    else:
                        resulttitle = title
                else:
                    resulttitle = title
                #
                duration = element['meta']['duration']
                #
                plot=""
                plot+="Tags: "
                #
                genres = []
                #
                for i, genre in enumerate(element['tags']):
                    genres.append(genre['title'])
                    plot+=genre['title']
                    if i != len(element['tags']) - 1:
                        plot+=", "
                #
                plot+="[CR][CR]" + self.localizeString(30011)
                #
                #self.logger.info('Tags: {} ; Variablentyp: {}', genres, type(genres))
                #
                pUI.addListItem(
                    pTitle=resulttitle,
                    pUrl=targetUrl,
                    pDuration=duration,
                    pIcon=element['urls']['thumbnail'],
                    pAired=element['created_at'],
                    pGenres=genres,
                    pPlot=plot,
                )
            #
            if 'nextlink' in element:
                targetUrl = pyUtils.build_url({
                    'mode': 'all',
                    'page': element['page'],
                })
                #self.logger.info('Weiterlink: {}', targetUrl)
                pUI.addDirectoryItem(
                    pTitle=self.localizeString(30012),
                    pUrl=targetUrl,
                    #pIcon=self.create_resource_path('media', 'next.png'),
                )
        #
        pUI.render()

    def genSubTags(self, pUI, pData):
        uData = pyUtils.makeDictUnique(pData, "id")
        for element in uData:
            #
            self.logger.info('genSubTags {}', element)
            tagid = element['tag_id']
            targetUrl = pyUtils.build_url({
                'mode': 'tag',
                'tagid': tagid,
            })
            #
            if element['title']:
                #
                title: str = element['title']
                #
                plot=""
                # plot+="Tags: "

                # genres = []

                # for i, genre in enumerate(element['tags']):
                #     genres.append(genre['title'])
                #     plot+=genre['title']
                #     if i != len(element['tags']) - 1:
                #         plot+=", "

                # plot+="[CR][CR]Schaue GRONKH live auf twitch.tv/GRONKH"

                #self.logger.info('Tags: {} ; Variablentyp: {}', genres, type(genres))

                pUI.addDirectoryItem(
                    pTitle=title,
                    pUrl=targetUrl,
                    pIcon=self.create_resource_path('media', 'tag.png'),
                    pPlot=plot,
                )

        #
        pUI.render()

    def remove_emojis(self, text):
        emoji_pattern = re.compile(
            "[" 
            "\U0001F600-\U0001F64F"  # Emoticons
            "\U0001F300-\U0001F5FF"  # Symbole & Piktogramme
            "\U0001F680-\U0001F6FF"  # Transport & Karten
            "\U0001F700-\U0001F77F"  # Alchemie etc.
            "\U0001F780-\U0001F7FF"  # Geometrische Symbole
            "\U0001F800-\U0001F8FF"  # Zusätzliche Symbole
            "\U0001F900-\U0001F9FF"  # Supplementäre Symbole & Pfeile
            "\U0001FA00-\U0001FA6F"  # Chess, Symbols
            "\U0001FA70-\U0001FAFF"  # Symbols
            "\U00002702-\U000027B0"  # Dingbats
            # "\U000024C2-\U0001F251"
            "]+", flags=re.UNICODE)
        return emoji_pattern.sub(r'', text)

