import xbmc
import xbmcaddon
import xbmcgui
import xbmcvfs
import glob
import os
import re

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

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

def net_tools():
    from resources.libs import speedtest
    directory.add_dir('Speed Test', {'mode': 'speedtest'}, icon=CONFIG.ICONNET)
    directory.add_separator(icon=CONFIG.ICONNET)
    mac, inter_ip, ip, city, state, country, isp = speedtest.net_info()
    directory.add_file('MAC: [COLORdeepskyblue]{2}[/COLOR]'.format(CONFIG.COLOR1, CONFIG.COLOR2, mac), icon=CONFIG.ICONNET)
    directory.add_file('Interne IP: [COLORdeepskyblue]{2}[/COLOR]'.format(CONFIG.COLOR1, CONFIG.COLOR2, inter_ip), icon=CONFIG.ICONNET)
    directory.add_file('Externe IP: [COLORdeepskyblue]{2}[/COLOR]'.format(CONFIG.COLOR1, CONFIG.COLOR2, ip), icon=CONFIG.ICONNET)	

def save_menu():
    on = '[COLORlime]AN[/COLOR]'
    off = '[COLORred]AUS[/COLOR]'

    login = 'true' if CONFIG.KEEPLOGIN == 'true' else 'false'
    sources = 'true' if CONFIG.KEEPSOURCES == 'true' else 'false'
    advanced = 'true' if CONFIG.KEEPADVANCED == 'true' else 'false'
    profiles = 'true' if CONFIG.KEEPPROFILES == 'true' else 'false'
    playercore = 'true' if CONFIG.KEEPPLAYERCORE == 'true' else 'false'
    guisettings = 'true' if CONFIG.KEEPGUISETTINGS == 'true' else 'false'
    favourites = 'true' if CONFIG.KEEPFAVS == 'true' else 'false'
    repos = 'true' if CONFIG.KEEPREPOS == 'true' else 'false'
    super = 'true' if CONFIG.KEEPSUPER == 'true' else 'false'
    whitelist = 'true' if CONFIG.KEEPWHITELIST == 'true' else 'false'

    directory.add_dir('Login Informationen bearbeiten', {'mode': 'login'}, icon=CONFIG.ICONLOGIN)
    directory.add_file('Gesicherte Daten importieren', {'mode': 'managedata', 'name': 'import'}, icon=CONFIG.ICONSAVE)
    directory.add_file('Gesicherte Daten exportieren', {'mode': 'managedata', 'name': 'export'}, icon=CONFIG.ICONSAVE)
    directory.add_separator(icon=CONFIG.ICONSAVE)	
    directory.add_file('[Backup] Login Informationen: {0}'.format(login.replace('true', on).replace('false', off)), {'mode': 'togglesetting', 'name': 'keeplogin'}, icon=CONFIG.ICONSAVE)
    directory.add_file('[Backup] \'Sources.xml\': {0}'.format(sources.replace('true', on).replace('false', off)), {'mode': 'togglesetting', 'name': 'keepsources'}, icon=CONFIG.ICONSAVE)
    directory.add_file('[Backup] \'Profiles.xml\': {0}'.format(profiles.replace('true', on).replace('false', off)), {'mode': 'togglesetting', 'name': 'keepprofiles'}, icon=CONFIG.ICONSAVE)
    directory.add_file('[Backup] \'Playercorefactory.xml\': {0}'.format(playercore.replace('true', on).replace('false', off)), {'mode': 'togglesetting', 'name': 'keepplayercore'}, icon=CONFIG.ICONSAVE)
    directory.add_file('[Backup] \'Advancedsettings.xml\': {0}'.format(advanced.replace('true', on).replace('false', off)), {'mode': 'togglesetting', 'name': 'keepadvanced'}, icon=CONFIG.ICONSAVE)
    directory.add_file('[Backup] \'Favourites.xml\': {0}'.format(favourites.replace('true', on).replace('false', off)), {'mode': 'togglesetting', 'name': 'keepfavourites'}, icon=CONFIG.ICONSAVE)
    directory.add_file('[Backup] \'Super Favourites\': {0}'.format(super.replace('true', on).replace('false', off)), {'mode': 'togglesetting', 'name': 'keepsuper'}, icon=CONFIG.ICONSAVE)
    directory.add_file('[Backup] \'Installierte Repos\': {0}'.format(repos.replace('true', on).replace('false', off)), {'mode': 'togglesetting', 'name': 'keeprepos'}, icon=CONFIG.ICONSAVE)
    directory.add_file('[Backup] \'WhiteList\': {0}'.format(whitelist.replace('true', on).replace('false', off)), {'mode': 'togglesetting', 'name': 'keepwhitelist'}, icon=CONFIG.ICONSAVE)
    if whitelist == 'true':
        directory.add_separator(icon=CONFIG.ICONSAVE)
        directory.add_file('Whitelist anzeigen', {'mode': 'whitelist', 'name': 'view'}, icon=CONFIG.ICONSAVE)
        directory.add_file('Whitelist bearbeiten', {'mode': 'whitelist', 'name': 'edit'}, icon=CONFIG.ICONSAVE)
        directory.add_file('Whitelist bereinigen', {'mode': 'whitelist', 'name': 'clear'}, icon=CONFIG.ICONSAVE)
        directory.add_file('Whitelist importieren', {'mode': 'whitelist', 'name': 'import'}, icon=CONFIG.ICONSAVE)
        directory.add_file('Whitelist exportieren', {'mode': 'whitelist', 'name': 'export'}, icon=CONFIG.ICONSAVE)

def login_menu():
    from resources.libs import loginit

    keep_login = '[COLORlime]AN[/COLOR]' if CONFIG.KEEPLOGIN == 'true' else '[COLORred]AUS[/COLOR]'
    last = str(CONFIG.LOGINSAVE) if not CONFIG.LOGINSAVE == '' else 'Login data hasn\'t been saved yet.'
    directory.add_file('[Backup] Login Informationen: {0}'.format(keep_login), {'mode': 'togglesetting', 'name': 'keeplogin'}, icon=CONFIG.ICONLOGIN)
    if CONFIG.KEEPLOGIN == 'true':
        directory.add_file('Letzte Sicherung: [COLORdeepskyblue]{0}[/COLOR]'.format(str(last)), icon=CONFIG.ICONLOGIN)
    directory.add_separator(icon=CONFIG.ICONLOGIN)

    for login in loginit.ORDER:
        if xbmc.getCondVisibility('System.HasAddon({0})'.format(loginit.LOGINID[login]['plugin'])):
            name = loginit.LOGINID[login]['name']
            path = loginit.LOGINID[login]['path']
            saved = loginit.LOGINID[login]['saved']
            file = loginit.LOGINID[login]['file']
            user = CONFIG.get_setting(saved)
            auser = loginit.login_user(login)
            icon = loginit.LOGINID[login]['icon'] if os.path.exists(path) else CONFIG.ICONLOGIN
            fanart = loginit.LOGINID[login]['fanart'] if os.path.exists(path) else CONFIG.ADDON_FANART
            menu = create_addon_data_menu('Login', login)
            menu2 = create_save_data_menu('Login', login)
            menu.append((CONFIG.THEME2.format('{0} Settings'.format(name)), 'RunPlugin(plugin://{0}/?mode=opensettings&name={1}&url=login)'.format(CONFIG.ADDON_ID, login)))

            directory.add_file('>>> [COLORdeepskyblue]{0}[/COLOR] <<<'.format(name), icon=icon, fanart=fanart)
            if not os.path.exists(path):
                directory.add_file('Addon: [COLORred]Nicht installiert[/COLOR]', icon=icon, fanart=fanart, menu=menu)
            elif not auser:
                directory.add_file('Addon: [COLORred]Nicht registriert[/COLOR]', {'mode': 'authlogin', 'name': login}, icon=icon, fanart=fanart, menu=menu)
            else:
                directory.add_file('Addon: [COLORlime]{0}[/COLOR]'.format(auser), {'mode': 'authlogin', 'name': login}, icon=icon, fanart=fanart, menu=menu)
            if user == "":
                if os.path.exists(file):
                    directory.add_file('[Backup]: [COLORred]Daten gefunden (importieren?)[/COLOR]', {'mode': 'importlogin', 'name': login}, icon=icon, fanart=fanart, menu=menu2)
                else:
                    directory.add_file('[Backup]: [COLORred]Keine[/COLOR]', {'mode': 'savelogin', 'name': login}, icon=icon, fanart=fanart, menu=menu2)
            else:
                directory.add_file('[Backup]: [COLORlime]{0}[/COLOR]'.format(user), icon=icon, fanart=fanart, menu=menu2)

    directory.add_separator(icon=CONFIG.ICONLOGIN)
    directory.add_file('[Backup] Alle Login Informationen', {'mode': 'savelogin', 'name': 'all'}, icon=CONFIG.ICONLOGIN)
    directory.add_file('[Restore] Alle Login Informationen', {'mode': 'restorelogin', 'name': 'all'}, icon=CONFIG.ICONLOGIN)
    directory.add_file('[Import] Alle Login Informationen', {'mode': 'importlogin', 'name': 'all'}, icon=CONFIG.ICONLOGIN)
    directory.add_file('[Clean] [COLORred]Alle Addon Login Informationen[/COLOR]', {'mode': 'addonlogin', 'name': 'all'}, icon=CONFIG.ICONLOGIN)
    directory.add_file('[Clean] [COLORred]Alle gesicherten Login Informationen[/COLOR]', {'mode': 'clearlogin', 'name': 'all'}, icon=CONFIG.ICONLOGIN)

def change_freq():
    from resources.libs.common import logging

    dialog = xbmcgui.Dialog()

    change = dialog.select("[COLORdeepskyblue]K.U.S[/COLOR] Wizard: Wähle den Intervall für die automatische Bereinigung".format(CONFIG.COLOR2), CONFIG.CLEANFREQ)
    if not change == -1:
        CONFIG.set_setting('autocleanfreq', str(change))
        logging.log_notify('Aktueller Intervall'.format(CONFIG.COLOR1),
                           '[COLORdeepskyblue]{1}[/COLOR]'.format(CONFIG.COLOR2, CONFIG.CLEANFREQ[change]))

def developer():
    directory.add_file('Test Update', {'mode': 'testupdate'}, icon=CONFIG.ICONDEV)
    directory.add_file('Test Build Prompt', {'mode': 'testbuildprompt'}, icon=CONFIG.ICONDEV)
    directory.add_file('Remove Non-Ascii filenames', {'mode': 'asciicheck'}, icon=CONFIG.ICONDEV)
    directory.add_file('Convert Paths to special', {'mode': 'convertpath'}, icon=CONFIG.ICONDEV)
    directory.add_file('Create QR Code', {'mode': 'createqr'}, icon=CONFIG.ICONDEV)
    directory.add_file('Reload Skin', {'mode': 'forceskin'}, icon=CONFIG.ICONDEV)
    directory.add_file('Reload Profile', {'mode': 'forceprofile'}, icon=CONFIG.ICONDEV)
    directory.add_file('Force Close Kodi', {'mode': 'forceclose'}, icon=CONFIG.ICONDEV)	

def create_addon_data_menu(add='', name=''):
    menu_items = []

    add2 = quote_plus(add.lower().replace(' ', ''))
    add3 = add.replace('Debrid', 'Real Debrid')
    name2 = quote_plus(name.lower().replace(' ', ''))
    name = name.replace('url', 'URL Resolver')
    menu_items.append((CONFIG.THEME2.format(name.title()), ' '))
    menu_items.append((CONFIG.THEME3.format('Save {0} Data'.format(add3)), 'RunPlugin(plugin://{0}/?mode=save{1}&name={2})'.format(CONFIG.ADDON_ID, add2, name2)))
    menu_items.append((CONFIG.THEME3.format('Restore {0} Data'.format(add3)), 'RunPlugin(plugin://{0}/?mode=restore{1}&name={2})'.format(CONFIG.ADDON_ID, add2, name2)))
    menu_items.append((CONFIG.THEME3.format('Clear {0} Data'.format(add3)), 'RunPlugin(plugin://{0}/?mode=clear{1}&name={2})'.format(CONFIG.ADDON_ID, add2, name2)))

    menu_items.append((CONFIG.THEME2.format('{0} Settings'.format(CONFIG.ADDONTITLE)), 'RunPlugin(plugin://{0}/?mode=settings)'.format(CONFIG.ADDON_ID)))

    return menu_items

def create_save_data_menu(add='', name=''):
    menu_items = []

    add2 = quote_plus(add.lower().replace(' ', ''))
    add3 = add.replace('Debrid', 'Real Debrid')
    name2 = quote_plus(name.lower().replace(' ', ''))
    name = name.replace('url', 'URL Resolver')
    menu_items.append((CONFIG.THEME2.format(name.title()), ' '))
    menu_items.append((CONFIG.THEME3.format('Register {0}'.format(add3)), 'RunPlugin(plugin://{0}/?mode=auth{1}&name={2})'.format(CONFIG.ADDON_ID, add2, name2)))
    menu_items.append((CONFIG.THEME3.format('Save {0} Data'.format(add3)), 'RunPlugin(plugin://{0}/?mode=save{1}&name={2})'.format(CONFIG.ADDON_ID, add2, name2)))
    menu_items.append((CONFIG.THEME3.format('Restore {0} Data'.format(add3)), 'RunPlugin(plugin://{0}/?mode=restore{1}&name={2})'.format(CONFIG.ADDON_ID, add2, name2)))
    menu_items.append((CONFIG.THEME3.format('Import {0} Data'.format(add3)), 'RunPlugin(plugin://{0}/?mode=import{1}&name={2})'.format(CONFIG.ADDON_ID, add2, name2)))
    menu_items.append((CONFIG.THEME3.format('Clear Addon {0} Data'.format(add3)), 'RunPlugin(plugin://{0}/?mode=addon{1}&name={2})'.format(CONFIG.ADDON_ID, add2, name2)))

    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  #
#                                                            #
##############################################################