import xbmc
import xbmcgui
import xbmcvfs
import os
import shutil
try:
    import zipfile
except ImportError:
    from resources.libs import zipfile

from resources.libs.common.config import CONFIG
from resources.libs.common import logging
from resources.libs.common import tools

def import_save_data():
    dialog = xbmcgui.Dialog()

    TEMP = os.path.join(CONFIG.PLUGIN_DATA, 'temp')
    if not os.path.exists(TEMP):
        os.makedirs(TEMP)
    source = dialog.browse(1, '[COLORdeepskyblue]K.U.S[/COLOR] Wizard: Wähle das Verzeichnis der gesicherten Daten'.format(CONFIG.COLOR2),
                               'files', '.zip', False, False, CONFIG.HOME)
    if not source.endswith('.zip'):
        logging.log_notify(CONFIG.ADDONTITLE,"Daten importieren: [COLORred]Fehler![/COLOR]".format(CONFIG.COLOR2))
        return
    source = xbmcvfs.translatePath(source)
    tempfile = xbmcvfs.translatePath(os.path.join(CONFIG.MYBUILDS, 'SaveData.zip'))
    if not tempfile == source:
        goto = xbmcvfs.copy(source, tempfile)

    from resources.libs import extract
    if not extract.all(xbmcvfs.translatePath(tempfile), TEMP):
        logging.log("Error trying to extract the zip file!")
        logging.log_notify(CONFIG.ADDONTITLE,"Daten importieren: [COLORred]Fehler![/COLOR]".format(CONFIG.COLOR2))
        return

    login = os.path.join(TEMP, 'login')
    super = os.path.join(TEMP, 'plugin.program.super.favourites')
    xmls = os.path.join(TEMP, 'xmls')

    x = 0
    overwrite = dialog.yesno(CONFIG.ADDONTITLE,"Willst du alle Dateien überschreiben oder nach jeder importierten Datei fragen?".format(CONFIG.COLOR2), yeslabel="[COLORlime]ALLE[/COLOR]", nolabel="[COLORred]EINZELN[/COLOR]")
    
    if os.path.exists(login):
        from resources.libs import loginit

        x += 1
        files = os.listdir(login)
        if not os.path.exists(CONFIG.LOGINFOLD):
            os.makedirs(CONFIG.LOGINFOLD)
        for item in files:
            old = os.path.join(CONFIG.LOGINFOLD, item)
            temp = os.path.join(login, item)
            if os.path.exists(old):
                if overwrite == 1:
                    os.remove(old)
                else:
                    if not dialog.yesno(CONFIG.ADDONTITLE,"Willst du die aktuellen Daten für [COLORdeepskyblue]{2}[/COLOR] überschreiben?".format(CONFIG.COLOR2, CONFIG.COLOR1, item), yeslabel="[COLORlime]JA[/COLOR]", nolabel="[COLORred]NEIN[/COLOR]"):
                        continue
                    else:
                        os.remove(old)
            shutil.copy(temp, old)
        loginit.import_list('all')
        loginit.login_it('restore', 'all')
    
    if os.path.exists(xmls):
        x += 1
        for item in CONFIG.XMLS:
            old = os.path.join(CONFIG.USERDATA, item)
            new = os.path.join(xmls, item)
            if not os.path.exists(new): continue
            if os.path.exists(old):
                if not overwrite == 1:
                    if not dialog.yesno(CONFIG.ADDONTITLE,"Willst du die aktuellen Daten für [COLORdeepskyblue]{2}[/COLOR] überschreiben?".format(CONFIG.COLOR2, CONFIG.COLOR1, item), yeslabel="[COLORlime]JA[/COLOR]", nolabel="[COLORred]NEIN[/COLOR]"):
                        continue
            os.remove(old)
            shutil.copy(new, old)
    if os.path.exists(super):
        x += 1
        old = os.path.join(CONFIG.ADDON_DATA, 'plugin.program.super.favourites')
        if os.path.exists(old):
            cont = dialog.yesno(CONFIG.ADDONTITLE,"Willst du den aktuellen [COLORdeepskyblue]Super Favourites AddonData-Ordner[/COLOR] überschreiben?".format(CONFIG.COLOR2, CONFIG.COLOR1), yeslabel="[COLORlime]JA[/COLOR]", nolabel="[COLORred]NEIN[/COLOR]")
        else:
            cont = 1
        if cont == 1:
            tools.clean_house(old)
            tools.remove_folder(old)
            xbmcvfs.copy(super, old)
    tools.clean_house(TEMP)
    tools.remove_folder(TEMP)
    if not tempfile == source:
        xbmcvfs.delete(tempfile)
    if x == 0:
        logging.log_notify(CONFIG.ADDONTITLE,"Daten importieren: [COLORred]Fehler![/COLOR]".format(CONFIG.COLOR2))
    else:
        logging.log_notify(CONFIG.ADDONTITLE,"Daten importieren: [COLORdeepskyblue]Abgeschlossen![/COLOR]".format(CONFIG.COLOR2))

def export_save_data():
    from resources.libs import loginit

    dialog = xbmcgui.Dialog()

    dir = ['login']
    keepx = [CONFIG.KEEPADVANCED, CONFIG.KEEPSOURCES, CONFIG.KEEPFAVS, CONFIG.KEEPPROFILES, CONFIG.KEEPPLAYERCORE, CONFIG.KEEPGUISETTINGS]
    loginit.login_it('update', 'all')
    source = dialog.browse(3, '[COLORdeepskyblue]K.U.S[/COLOR] Wizard: Wähle ein Verzeichnis für den Export'.format(CONFIG.COLOR2),
                               'files', '', False, True, CONFIG.HOME)
    source = xbmcvfs.translatePath(source)
    tempzip = os.path.join(source, 'SaveData.zip')
    superfold = os.path.join(CONFIG.ADDON_DATA, 'plugin.program.super.favourites')
    zipf = zipfile.ZipFile(tempzip, mode='w', allowZip64=True)
    for fold in dir:
        path = os.path.join(CONFIG.PLUGIN_DATA, fold)
        if os.path.exists(path):
            files = os.listdir(path)
            for file in files:
                fn = os.path.join(path, file)
                zipf.write(fn, os.path.join(fold, file), zipfile.ZIP_DEFLATED)
    if CONFIG.KEEPSUPER == 'true' and os.path.exists(superfold):
        for base, dirs, files in os.walk(superfold):
            for file in files:
                fn = os.path.join(base, file)
                zipf.write(fn, fn[len(CONFIG.ADDON_DATA):], zipfile.ZIP_DEFLATED)
    for item in CONFIG.XMLS:
        if keepx[CONFIG.XMLS.index(item)] == 'true' and os.path.exists(os.path.join(CONFIG.USERDATA, item)):
            zipf.write(os.path.join(CONFIG.USERDATA, item), os.path.join('xmls', item), zipfile.ZIP_DEFLATED)
    zipf.close()
    
    dialog.ok(CONFIG.ADDONTITLE,"Die Daten wurden in folgendes Verzeichnis exportiert:".format(CONFIG.COLOR2)+'\n'+"[COLORdeepskyblue]{1}[/COLOR]".format(CONFIG.COLOR1, os.path.join(source, 'SaveData.zip')))

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