import xbmc
import xbmcgui
import os

from resources.libs import check
from resources.libs import db
from resources.libs import extract
from resources.libs import install
from resources.libs import skin
from resources.libs.common import logging
from resources.libs.common import tools
from resources.libs.common.config import CONFIG
from resources.libs.downloader import Downloader

class Wizard:

    def __init__(self):
        tools.ensure_folders(CONFIG.PACKAGES)
        
        self.dialog = xbmcgui.Dialog()
        self.dialogProgress = xbmcgui.DialogProgress()

    def _prompt_for_wipe(self):
        # Should we wipe first?
        if self.dialog.yesno(CONFIG.ADDONTITLE,"Willst du Kodi auf Werkseinstellung zurücksetzen,".format(CONFIG.COLOR2) + '\n' + "bevor du das Build installierst?", nolabel='[COLORred]NEIN[/COLOR]', yeslabel='[COLORlime]JA[/COLOR]'):
            install.wipe()

    def build(self, name, over=False):
        # if action == 'normal':
            # if CONFIG.KEEPTRAKT == 'true':
                # from resources.libs import traktit
                # traktit.auto_update('all')
                # CONFIG.set_setting('traktnextsave', tools.get_date(days=3, formatted=True))
            # if CONFIG.KEEPDEBRID == 'true':
                # from resources.libs import debridit
                # debridit.auto_update('all')
                # CONFIG.set_setting('debridnextsave', tools.get_date(days=3, formatted=True))
            # if CONFIG.KEEPLOGIN == 'true':
                # from resources.libs import loginit
                # loginit.auto_update('all')
                # CONFIG.set_setting('loginnextsave', tools.get_date(days=3, formatted=True))

        temp_kodiv = int(CONFIG.KODIV)
        buildv = int(float(check.check_build(name, 'kodi')))

        if not temp_kodiv == buildv:
            warning = True
        else:
            warning = False

        if warning:
            yes_pressed = self.dialog.yesno("{0} - [COLORred]WARNUNG![/COLOR]".format(CONFIG.ADDONTITLE), 'Es besteht die Möglichkeit, dass der Skin nicht richtig funktioniert'.format(CONFIG.COLOR2) + '\n' + 'wenn du ein [COLORdeepskyblue]{0}[/COLOR] Build auf Kodi [COLORdeepskyblue{1}[/COLOR] installierst.'.format(check.check_build(name, 'kodi'), CONFIG.KODIV) + '\n' + 'Willst du wirklich [COLORdeepskyblue]{1} v.{2}[/COLOR] installieren?'.format(CONFIG.COLOR1, name, check.check_build(name, 'version')), nolabel='[COLORred]NEIN[/COLOR]', yeslabel='[COLORlime]JA[/COLOR]')
        else:
            if over:
                yes_pressed = 1
            else:
                yes_pressed = self.dialog.yesno(CONFIG.ADDONTITLE, 'Willst du [COLORdeepskyblue]{1} v.{2}[/COLOR] laden und installieren?'.format(CONFIG.COLOR1, name, check.check_build(name,'version')), nolabel='[COLORred]NEIN[/COLOR]', yeslabel='[COLORlime]JA[/COLOR]')
        if yes_pressed:
            CONFIG.clear_setting('build')
            buildzip = check.check_build(name, 'url')
            zipname = name.replace('\\', '').replace('/', '').replace(':', '').replace('*', '').replace('?', '').replace('"', '').replace('<', '').replace('>', '').replace('|', '')

            self.dialogProgress.create(CONFIG.ADDONTITLE, '[COLORdeepskyblue]{2} v.{3}[/COLOR] wird heruntergeladen.'.format(CONFIG.COLOR2, CONFIG.COLOR1, name, check.check_build(name, 'version')) + '\n' + 'Bitte warten...')

            lib = os.path.join(CONFIG.MYBUILDS, '{0}.zip'.format(zipname))
            
            try:
                os.remove(lib)
            except:
                pass

            Downloader().download(buildzip, lib)
            xbmc.sleep(500)
            
            if os.path.getsize(lib) == 0:
                try:
                    os.remove(lib)
                except:
                    pass
                    
                return
                
            install.wipe()
                
            skin.look_and_feel_data('save')
            
            title = '[COLORdeepskyblue]{2} v.{3}[/COLOR] wird installiert.'.format(CONFIG.COLOR2, CONFIG.COLOR1, name, check.check_build(name, 'version'))
            self.dialogProgress.update(0, title + '\n' + 'Bitte warten...')
            percent, errors, error = extract.all(lib, CONFIG.HOME, title=title)
            
            skin.skin_to_default('Build Install')

            if int(float(percent)) > 0:
                db.fix_metas()
                CONFIG.set_setting('buildname', name)
                CONFIG.set_setting('buildversion', check.check_build(name, 'version'))
                CONFIG.set_setting('latestversion', check.check_build(name, 'version'))
                CONFIG.set_setting('nextbuildcheck', tools.get_date(days=CONFIG.UPDATECHECK, formatted=True))
                CONFIG.set_setting('installed', 'true')
                CONFIG.set_setting('extract', percent)
                CONFIG.set_setting('errors', errors)
                logging.log('INSTALLED {0}: [ERRORS:{1}]'.format(percent, errors))

                try:
                    os.remove(lib)
                except:
                    pass

                if int(float(errors)) > 0:
                    yes_pressed = self.dialog.yesno(CONFIG.ADDONTITLE,'[COLORdeepskyblue]{2} v.{3}[/COLOR]'.format(CONFIG.COLOR2, CONFIG.COLOR1, name, check.check_build(name, 'version')) +'\n' + 'Installiert: [COLORdeepskyblue]{1}{2}[/COLOR] [Fehler: [COLORred]{4}[/COLOR]]'.format(CONFIG.COLOR1, percent, '%', CONFIG.COLOR1, errors) + '\n' + 'Willst du dir die Fehler ansehen?', nolabel='[COLORred]NEIN[/COLOR]', yeslabel='[COLORlime]JA[/COLOR]')
                    if yes_pressed:
                        from resources.libs.gui import window
                        window.show_text_box("Fehler bei der Installation", error)
                self.dialogProgress.close()

                from resources.libs.gui.build_menu import BuildMenu

                db.addon_database(CONFIG.ADDON_ID, 1)
                db.force_check_updates(over=True)
                if os.path.exists(os.path.join(CONFIG.USERDATA, '.enableall')):
                	CONFIG.set_setting('enable_all', 'true')

                self.dialog.ok(CONFIG.ADDONTITLE, "Um Änderungen zu speichern, muss Kodi beendet werden. Drücke OK um Kodi zu beenden.".format(CONFIG.COLOR2))
                tools.kill_kodi(over=True)
            else:
                from resources.libs.gui import window
                window.show_text_box("Fehler bei der Installation", error)
        else:
            logging.log_notify(CONFIG.ADDONTITLE,'Build Installation: [COLORdeepskyblue]Abgebrochen![/COLOR]'.format(CONFIG.COLOR2))

def wizard(action, name, url):
    cls = Wizard()

    if action in ['fresh', 'normal']:
        cls.build(action, name)
    elif action == 'gui':
        cls.gui(name)

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