import re

try:
    from urllib.parse import quote_plus
except ImportError:
    from urllib import quote_plus

from resources.libs import check
from resources.libs.common import directory
from resources.libs.common import tools
from resources.libs.common.config import CONFIG

class BuildMenu:

    def _list_all(self, match, kodiv=None):
        from resources.libs import test

        for name, version, url, gui, kodi, theme, icon, fanart, adult, description in match:
            if not CONFIG.SHOWADULT == 'true' and adult.lower() == 'yes':
                continue
            if not CONFIG.DEVELOPER == 'true' and test.str_test(name):
                continue

            if not kodiv or kodiv == int(float(kodi)):
                menu = self.create_install_menu(name)
                directory.add_dir('> {1} (v.{2})'.format(float(kodi), name, version), {'mode': 'viewbuild', 'name': name}, description=description, fanart=fanart, icon=icon, menu=menu)

        from resources.libs import check
        from resources.libs.common import tools

    def get_listing(self):
        from resources.libs import test
        
        response = tools.open_url(CONFIG.BUILDFILE)
        
        if response:
            link = tools.clean_text(response.text)
        else:
            directory.add_file('Kodi Version: {0}'.format(CONFIG.KODIV), icon=CONFIG.ICONBUILDS,
                               themeit=CONFIG.THEME3)
            directory.add_dir('Save Data Menu', {'mode': 'savedata'}, icon=CONFIG.ICONSAVE, themeit=CONFIG.THEME3)
            directory.add_separator()
            directory.add_file('URL for txt file not valid', icon=CONFIG.ICONBUILDS, themeit=CONFIG.THEME3)
            directory.add_file('{0}'.format(CONFIG.BUILDFILE), icon=CONFIG.ICONBUILDS, themeit=CONFIG.THEME3)
            return

        total, count23, count22, count21, adultcount, hidden = check.build_count()

        match = re.compile('name="(.+?)".+?ersion="(.+?)".+?rl="(.+?)".+?ui="(.+?)".+?odi="(.+?)".+?heme="(.+?)".+?con="(.+?)".+?anart="(.+?)".+?dult="(.+?)".+?escription="(.+?)"').findall(link)
        
        if total == 1:
            for name, version, url, gui, kodi, theme, icon, fanart, adult, description in match:
                if not CONFIG.SHOWADULT == 'true' and adult.lower() == 'yes':
                    continue
                if not CONFIG.DEVELOPER == 'true' and test.str_test(name):
                    continue

                self.view_build(match[0][0])
                return

        directory.add_file('Installierte Kodi Version: [COLORdeepskyblue]v.{0}[/COLOR]'.format(CONFIG.KODIV), icon=CONFIG.ICONBUILDS)
        directory.add_separator(icon=CONFIG.ICONBUILDS)

        if len(match) >= 1:
            if CONFIG.SEPARATE == 'true':
                self._list_all(match)
            else:
                if count21 > 0:
                    state = '+' if CONFIG.SHOW21 == 'false' else '-'
                    directory.add_file('[COLORdeepskyblue][Kodi 21] Omega Builds ({1})[/COLOR]'.format(state, count21), {'mode': 'togglesetting','name': 'show21'}, icon=CONFIG.ICONBUILDS)
                    if CONFIG.SHOW21 == 'true':
                        self._list_all(match, kodiv=21)						
                if count22 > 0:
                    state = '+' if CONFIG.SHOW22 == 'false' else '-'
                    directory.add_file('[COLORdeepskyblue][Kodi 22] Piers Builds ({1})[/COLOR]'.format(state, count22), {'mode': 'togglesetting','name': 'show22'})
                    if CONFIG.SHOW22 == 'true':
                        self._list_all(match, kodiv=22)						
                if count23 > 0:
                    state = '+' if CONFIG.SHOW23 == 'false' else '-'
                    directory.add_file('[COLORdeepskyblue][Kodi 23] Quest Builds ({1})[/COLOR]'.format(state, count23), {'mode': 'togglesetting','name': 'show23'})
                    if CONFIG.SHOW23 == 'true':
                        self._list_all(match, kodiv=23)

        elif hidden > 0:
            if adultcount > 0:
                directory.add_file('There is currently only Adult builds', icon=CONFIG.ICONBUILDS)
                directory.add_file('Enable Show Adults in Addon Settings > Misc', icon=CONFIG.ICONBUILDS)
            else:
                directory.add_file('Currently No Builds Offered from {0}'.format(CONFIG.ADDONTITLE),icon=CONFIG.ICONBUILDS)
        else:
            directory.add_file('Text file for builds not formatted correctly.', icon=CONFIG.ICONBUILDS)

    def view_build(self, name):
    
        response = tools.open_url(CONFIG.BUILDFILE)
        
        if response:
            link = tools.clean_text(response.text)
        else:
            directory.add_file('URL for txt file not valid')
            directory.add_file('{0}'.format(CONFIG.BUILDFILE))
            return

        if not check.check_build(name, 'version'):
            directory.add_file('Error reading the txt file.')
            directory.add_file('{0} was not found in the builds list.'.format(name))
            return

        match = re.compile(
            'name="%s".+?ersion="(.+?)".+?rl="(.+?)".+?ui="(.+?)".+?odi="(.+?)".+?heme="(.+?)".+?con="(.+?)".+?anart="(.+?)".+?review="(.+?)".+?dult="(.+?)".+?nfo="(.+?)".+?escription="(.+?)"' % name).findall(
            link)
            
        for version, url, gui, kodi, themefile, icon, fanart, preview, adult, info, description in match:
            build = '[COLORdeepskyblue]{0} (v.{1})[/COLOR]'.format(name, version)
            
            updatecheck = CONFIG.BUILDNAME == name and version > CONFIG.BUILDVERSION
            versioncheck = True if float(CONFIG.KODIV) == float(kodi) else False
            previewcheck = tools.open_url(preview, check=True)
            guicheck = tools.open_url(gui, check=True)
            
            if updatecheck:
                build = '{0} [COLORred][Aktuell v.{1}][/COLOR]'.format(build, CONFIG.BUILDVERSION)
                
            directory.add_file(build, description=description, fanart=fanart, icon=icon)
            directory.add_file('Build Informationen', {'mode': 'buildinfo', 'name': name}, description=description, fanart=fanart,icon=icon)
            directory.add_dir('Daten sichern vor der Installation', {'mode': 'savedata'}, description=description, fanart=fanart,icon=icon)			
            directory.add_separator(fanart=fanart, icon=icon)            
            if versioncheck:
                directory.add_file('[I][COLORred]Das Build ist für Kodi v.{0} erstellt / (installiert: v.{1})[/COLOR][/I]'.format(str(kodi), str(CONFIG.KODIV)), description=description, fanart=fanart, icon=icon)
            directory.add_file('[B]>>>[/B] [COLORdeepskyblue]Installieren[/COLOR] [B]<<<[/B]', {'mode': 'install', 'action': 'build', 'name': name}, description=description, fanart=fanart,icon=icon)

    def build_info(self, name):
        from resources.libs import check
        from resources.libs.common import logging
        from resources.libs.common import tools
        from resources.libs.gui import window
        
        response = tools.open_url(CONFIG.BUILDFILE, check=True)
        
        if response:
            if check.check_build(name, 'url'):
                name, version, url, minor, gui_ignore, kodi, theme, icon, fanart, preview, adult, info, description = check.check_build(name, 'all')
                adult = 'Ja' if adult.lower() == 'JA' else 'NEIN'

                info_response = tools.open_url(info)

                if info_response:
                    try:
                        tname, extracted, zipsize, skin, created, programs, video, music, picture, repos, scripts, binaries = check.check_info(info_response.text)
                        extend = True
                    except:
                        extend = False
                else:
                    extend = False

                msg = "Kodi Version: [COLORdeepskyblue]{2}[/COLOR][CR]".format(CONFIG.COLOR2, CONFIG.COLOR1, kodi)
                msg += "Build Name: [COLORdeepskyblue]{2}[/COLOR][CR]".format(CONFIG.COLOR2, CONFIG.COLOR1, name)
                msg += "Build Version: [COLORdeepskyblue]{2}[/COLOR][CR]".format(CONFIG.COLOR2, CONFIG.COLOR1, version)
                msg += "Build Beschreibung: [COLORdeepskyblue]{2}[/COLOR][CR][CR]".format(CONFIG.COLOR2, CONFIG.COLOR1, description)				
                msg += "Zip Größe: [COLORdeepskyblue]{2}[/COLOR][CR]".format(CONFIG.COLOR2, CONFIG.COLOR1, tools.convert_size(int(float(zipsize))))
                msg += "Entpackte Größe: [COLORdeepskyblue]{2}[/COLOR][CR]".format(CONFIG.COLOR2, CONFIG.COLOR1, tools.convert_size(int(float(extracted))))				
                msg += "Letztes Update: [COLORdeepskyblue]{2}[/COLOR][CR][CR]".format(CONFIG.COLOR2, CONFIG.COLOR1, created)
                msg += "Erwachsenen Inhalt: [COLORdeepskyblue]{2}[/COLOR][CR][CR]".format(CONFIG.COLOR2, CONFIG.COLOR1, adult)				

                if extend:
                    msg += "Skin Name: [COLORdeepskyblue]{2}[/COLOR][CR][CR]".format(CONFIG.COLOR2, CONFIG.COLOR1, skin)
                    msg += "Program-Addons: [COLORdeepskyblue]{2}[/COLOR][CR][CR]".format(CONFIG.COLOR2, CONFIG.COLOR1, programs)
                    msg += "Video-Addons: [COLORdeepskyblue]{2}[/COLOR][CR][CR]".format(CONFIG.COLOR2, CONFIG.COLOR1, video)
                    msg += "Musik-Addons: [COLORdeepskyblue]{2}[/COLOR][CR][CR]".format(CONFIG.COLOR2, CONFIG.COLOR1, music)
                    msg += "Bilder-Addons: [COLORdeepskyblue]{2}[/COLOR][CR][CR]".format(CONFIG.COLOR2, CONFIG.COLOR1, picture)
                    msg += "Repositories: [COLORdeepskyblue]{2}[/COLOR][CR][CR]".format(CONFIG.COLOR2, CONFIG.COLOR1, repos)
                    msg += "Scripte: [COLORdeepskyblue]{2}[/COLOR][CR][CR]".format(CONFIG.COLOR2, CONFIG.COLOR1, scripts)
                    msg += "Abhängigkeiten: [COLORdeepskyblue]{2}[/COLOR]".format(CONFIG.COLOR2, CONFIG.COLOR1, binaries)

                window.show_text_box("Build Informationen: [COLORdeepskyblue]{0}[/COLOR]".format(name), msg)
            else:
                logging.log("Invalid Build Name!")
        else:
            logging.log("Build text file not working: {0}".format(CONFIG.BUILDFILE))

    def build_video(self, name):
        from resources.libs import check
        from resources.libs import yt
        from resources.libs.common import logging
        from resources.libs.common import tools
        
        response = tools.open_url(CONFIG.BUILDFILE, check=True)
        
        if response:
            videofile = check.check_build(name, 'preview')
            if tools.open_url(videofile, check=True):
                yt.play_video(videofile)
            else:
                logging.log("[{0}]Unable to find url for video preview".format(name))
        else:
            logging.log("Build text file not working: {0}".format(CONFIG.BUILDFILE))

    def create_install_menu(self, name):
        menu_items = []

        buildname = quote_plus(name)
        menu_items.append((CONFIG.THEME2.format(name), 'RunAddon({0}, ?mode=viewbuild&name={1})'.format(CONFIG.ADDON_ID, buildname)))
        menu_items.append((CONFIG.THEME3.format('Fresh Install'), 'RunPlugin(plugin://{0}/?mode=install&name={1}&url=fresh)'.format(CONFIG.ADDON_ID, buildname)))
        menu_items.append((CONFIG.THEME3.format('Normal Install'), 'RunPlugin(plugin://{0}/?mode=install&name={1}&url=normal)'.format(CONFIG.ADDON_ID, buildname)))
        menu_items.append((CONFIG.THEME3.format('Build Information'), 'RunPlugin(plugin://{0}/?mode=buildinfo&name={1})'.format(CONFIG.ADDON_ID, buildname)))
        menu_items.append((CONFIG.THEME2.format('{0} Settings'.format(CONFIG.ADDONTITLE)), 'RunPlugin(plugin://{0}/?mode=settings)'.format(CONFIG.ADDON_ID)))

        return menu_items

##############################################################
#                                                            #
#  Copyright (C) 2025 SGKodi / Kodi Unlimited Support Group  #
#                                                            #
##############################################################		