# -*- coding: UTF-8 -*-

import os, re, shutil, time, xbmc
from resources.lib.modules import control
try: import json as simplejson 
except: import simplejson


ADDONS = os.path.join(control.HOMEPATH, 'addons')


def currSkin():
    return control.skin


def getOld(old):
    try:
        old = '"%s"' % old
        query = '{"jsonrpc":"2.0", "method":"Settings.GetSettingValue","params":{"setting":%s}, "id":1}' % (old)
        response = control.jsonrpc(query)
        response = simplejson.loads(response)
        if response.has_key('result'):
            if response['result'].has_key('value'):
                return response ['result']['value']
    except:
        pass
    return None


def setNew(new, value):
    try:
        new = '"%s"' % new
        value = '"%s"' % value
        query = '{"jsonrpc":"2.0", "method":"Settings.SetSettingValue","params":{"setting":%s,"value":%s}, "id":1}' % (new, value)
        response = control.jsonrpc(query)
    except:
        pass
    return None


def swapSkins(skin):
    old = 'lookandfeel.skin'
    value = skin
    current = getOld(old)
    new = old
    setNew(new, value)


def lookandFeelData(do='save'):
    scan = ['lookandfeel.enablerssfeeds', 'lookandfeel.font', 'lookandfeel.rssedit', 'lookandfeel.skincolors', 'lookandfeel.skintheme', 'lookandfeel.skinzoom', 'lookandfeel.soundskin', 'lookandfeel.startupwindow', 'lookandfeel.stereostrength']
    if do == 'save':
        for item in scan:
            query = '{"jsonrpc":"2.0", "method":"Settings.GetSettingValue","params":{"setting":"%s"}, "id":1}' % (item)
            response = control.jsonrpc(query)
            if not 'error' in response:
                match = re.compile('{"value":(.+?)}').findall(str(response))
                control.setSetting(item.replace('lookandfeel', 'default'), match[0])
                control.log("%s saved to %s" % (item, match[0]))
    else:
        for item in scan:
            value = setting(item.replace('lookandfeel', 'default'))
            query = '{"jsonrpc":"2.0", "method":"Settings.SetSettingValue","params":{"setting":"%s","value":%s}, "id":1}' % (item, value)
            response = control.jsonrpc(query)
            control.log("%s restored to %s" % (item, value))


def defaultSkin():
    control.log("[Default Skin Check]")
    tempgui = os.path.join(USERDATAPATH, 'guitemp.xml')
    gui = tempgui if os.path.exists(tempgui) else GUISETTINGS
    if not os.path.exists(gui): return False
    control.log("Reading gui file: %s" % gui)
    guif = open(gui, 'r+')
    msg = guif.read().replace('\n','').replace('\r','').replace('\t','').replace('    ',''); guif.close()
    control.log("Opening gui settings")
    match = re.compile('<lookandfeel>.+?<ski.+?>(.+?)</skin>.+?</lookandfeel>').findall(msg)
    control.log("Matches: %s" % str(match))
    if len(match) > 0:
        skinid = match[0]
        addonxml = os.path.join(ADDONS, match[0], 'addon.xml')
        if os.path.exists(addonxml):
            addf = open(addonxml, 'r+')
            msg2 = addf.read().replace('\n','').replace('\r','').replace('\t',''); addf.close()
            match2 = re.compile('<addon.+?ame="(.+?)".+?>').findall(msg2)
            if len(match2) > 0: skinname = match2[0]
            else: skinname = 'no match'
        else: skinname = 'no file'
        control.log("[Default Skin Check] Skin name: %s" % skinname)
        control.log("[Default Skin Check] Skin id: %s" % skinid)
        control.setSetting('defaultskin', skinid)
        control.setSetting('defaultskinname', skinname)
        control.setSetting('defaultskinignore', 'false')
    if os.path.exists(tempgui):
        control.log("Deleting Temp Gui File.")
        os.remove(tempgui)
    control.log("[Default Skin Check] End")


def checkSkin():
    control.loga("Invalid Skin Check Start")
    DEFAULTSKIN = setting('defaultskin')
    DEFAULTNAME = setting('defaultskinname')
    DEFAULTIGNORE = setting('defaultskinignore')
    gotoskin = False
    if not DEFAULTSKIN == '':
        if os.path.exists(os.path.join(ADDONS, DEFAULTSKIN)):
            if DIALOG.yesno(AddonTitle, "[COLOR %s]It seems that the skin has been set back to [COLOR %s]%s[/COLOR]" % (COLOR2, COLOR1, SKIN[5:].title()), "Would you like to set the skin back to:[/COLOR]", '[COLOR %s]%s[/COLOR]' % (COLOR1, DEFAULTNAME)):
                gotoskin = DEFAULTSKIN
                gotoname = DEFAULTNAME
            else: control.loga("Skin was not reset"); control.setSetting('defaultskinignore', 'true'); gotoskin = False
        else: control.setSetting('defaultskin', ''); control.setSetting('defaultskinname', ''); DEFAULTSKIN = ''; DEFAULTNAME = ''
    if DEFAULTSKIN == '':
        skinname = []
        skinlist = []
        for folder in glob.glob(os.path.join(ADDONS, 'skin.*/')):
            xml = "%s/addon.xml" % folder
            if os.path.exists(xml):
                f  = open(xml,mode='r'); g = f.read().replace('\n','').replace('\r','').replace('\t',''); f.close();
                match = re.compile('<addon.+?id="(.+?)".+?>').findall(g)
                match2 = re.compile('<addon.+?name="(.+?)".+?>').findall(g)
                control.loga("%s: %s" % (folder, str(match[0])))
                if len(match) > 0: skinlist.append(str(match[0])); skinname.append(str(match2[0]))
                else: control.loga("ID not found for %s" % folder)
            else: control.loga("ID not found for %s" % folder)
        if len(skinlist) > 0:
            if len(skinlist) > 1:
                if DIALOG.yesno(control.AddonTitle, "[COLOR %s]It seems that the skin has been set back to [COLOR %s]%s[/COLOR]" % (COLOR2, COLOR1, SKIN[5:].title()), "Would you like to view a list of avaliable skins?[/COLOR]"):
                    choice = DIALOG.select("Select skin to switch to!", skinname)
                    if choice == -1: control.loga("Skin was not reset"); control.setSetting('defaultskinignore', 'true')
                    else: 
                        gotoskin = skinlist[choice]
                        gotoname = skinname[choice]
                else: control.loga("Skin was not reset"); control.setSetting('defaultskinignore', 'true')
            else:
                if DIALOG.yesno(control.AddonTitle, "It seems that the skin has been set back to [B]%s[/B]" % (SKIN[5:].title()), "Would you like to set the skin back to: ", '[B] %s [/B]' % (skinname[0])):
                    gotoskin = skinlist[0]
                    gotoname = skinname[0]
                else: control.loga("Skin was not reset"); control.setSetting('defaultskinignore', 'true')
        else: control.loga("No skins found in addons folder."); control.setSetting('defaultskinignore', 'true'); gotoskin = False
    if gotoskin:
        swapSkins(gotoskin)
        x = 0
        control.sleep(1000)
        while not control.condVisibility("Window.isVisible(yesnodialog)") and x < 150:
            x += 1
            control.sleep(200)
        if control.condVisibility("Window.isVisible(yesnodialog)"):
            control.execute('SendClick(11)')
            lookandFeelData('restore')
        else: control.Notify(control.AddonTitle,'Skin Swap Timed Out!')
    control.loga("Invalid Skin Check End")



[((170, 210), 'os.path.join', 'os.path.join', (['control.HOMEPATH', '"""addons"""'], {}), "(control.HOMEPATH, 'addons')\n", (182, 210), False, 'import os, re, shutil, time, xbmc\n'), ((2264, 2299), 'resources.lib.modules.control.log', 'control.log', (['"""[Default Skin Check]"""'], {}), "('[Default Skin Check]')\n", (2275, 2299), False, 'from resources.lib.modules import control\n'), ((2314, 2355), 'os.path.join', 'os.path.join', (['USERDATAPATH', '"""guitemp.xml"""'], {}), "(USERDATAPATH, 'guitemp.xml')\n", (2326, 2355), False, 'import os, re, shutil, time, xbmc\n'), ((2467, 2508), 'resources.lib.modules.control.log', 'control.log', (["('Reading gui file: %s' % gui)"], {}), "('Reading gui file: %s' % gui)\n", (2478, 2508), False, 'from resources.lib.modules import control\n'), ((2646, 2681), 'resources.lib.modules.control.log', 'control.log', (['"""Opening gui settings"""'], {}), "('Opening gui settings')\n", (2657, 2681), False, 'from resources.lib.modules import control\n'), ((3610, 3633), 'os.path.exists', 'os.path.exists', (['tempgui'], {}), '(tempgui)\n', (3624, 3633), False, 'import os, re, shutil, time, xbmc\n'), ((3713, 3752), 'resources.lib.modules.control.log', 'control.log', (['"""[Default Skin Check] End"""'], {}), "('[Default Skin Check] End')\n", (3724, 3752), False, 'from resources.lib.modules import control\n'), ((3776, 3816), 'resources.lib.modules.control.loga', 'control.loga', (['"""Invalid Skin Check Start"""'], {}), "('Invalid Skin Check Start')\n", (3788, 3816), False, 'from resources.lib.modules import control\n'), ((7154, 7192), 'resources.lib.modules.control.loga', 'control.loga', (['"""Invalid Skin Check End"""'], {}), "('Invalid Skin Check End')\n", (7166, 7192), False, 'from resources.lib.modules import control\n'), ((440, 462), 'resources.lib.modules.control.jsonrpc', 'control.jsonrpc', (['query'], {}), '(query)\n', (455, 462), False, 'from resources.lib.modules import control\n'), ((482, 508), 'simplejson.loads', 'simplejson.loads', (['response'], {}), '(response)\n', (498, 508), False, 'import simplejson\n'), ((936, 958), 'resources.lib.modules.control.jsonrpc', 'control.jsonrpc', (['query'], {}), '(query)\n', (951, 958), False, 'from resources.lib.modules import control\n'), ((2377, 2400), 'os.path.exists', 'os.path.exists', (['tempgui'], {}), '(tempgui)\n', (2391, 2400), False, 'import os, re, shutil, time, xbmc\n'), ((2429, 2448), 'os.path.exists', 'os.path.exists', (['gui'], {}), '(gui)\n', (2443, 2448), False, 'import os, re, shutil, time, xbmc\n'), ((2887, 2930), 'os.path.join', 'os.path.join', (['ADDONS', 'match[0]', '"""addon.xml"""'], {}), "(ADDONS, match[0], 'addon.xml')\n", (2899, 2930), False, 'import os, re, shutil, time, xbmc\n'), ((2942, 2966), 'os.path.exists', 'os.path.exists', (['addonxml'], {}), '(addonxml)\n', (2956, 2966), False, 'import os, re, shutil, time, xbmc\n'), ((3314, 3374), 'resources.lib.modules.control.log', 'control.log', (["('[Default Skin Check] Skin name: %s' % skinname)"], {}), "('[Default Skin Check] Skin name: %s' % skinname)\n", (3325, 3374), False, 'from resources.lib.modules import control\n'), ((3383, 3439), 'resources.lib.modules.control.log', 'control.log', (["('[Default Skin Check] Skin id: %s' % skinid)"], {}), "('[Default Skin Check] Skin id: %s' % skinid)\n", (3394, 3439), False, 'from resources.lib.modules import control\n'), ((3448, 3489), 'resources.lib.modules.control.setSetting', 'control.setSetting', (['"""defaultskin"""', 'skinid'], {}), "('defaultskin', skinid)\n", (3466, 3489), False, 'from resources.lib.modules import control\n'), ((3498, 3545), 'resources.lib.modules.control.setSetting', 'control.setSetting', (['"""defaultskinname"""', 'skinname'], {}), "('defaultskinname', skinname)\n", (3516, 3545), False, 'from resources.lib.modules import control\n'), ((3554, 3602), 'resources.lib.modules.control.setSetting', 'control.setSetting', (['"""defaultskinignore"""', '"""false"""'], {}), "('defaultskinignore', 'false')\n", (3572, 3602), False, 'from resources.lib.modules import control\n'), ((3643, 3681), 'resources.lib.modules.control.log', 'control.log', (['"""Deleting Temp Gui File."""'], {}), "('Deleting Temp Gui File.')\n", (3654, 3681), False, 'from resources.lib.modules import control\n'), ((3690, 3708), 'os.remove', 'os.remove', (['tempgui'], {}), '(tempgui)\n', (3699, 3708), False, 'import os, re, shutil, time, xbmc\n'), ((6769, 6788), 'resources.lib.modules.control.sleep', 'control.sleep', (['(1000)'], {}), '(1000)\n', (6782, 6788), False, 'from resources.lib.modules import control\n'), ((6937, 6992), 'resources.lib.modules.control.condVisibility', 'control.condVisibility', (['"""Window.isVisible(yesnodialog)"""'], {}), "('Window.isVisible(yesnodialog)')\n", (6959, 6992), False, 'from resources.lib.modules import control\n'), ((1600, 1622), 'resources.lib.modules.control.jsonrpc', 'control.jsonrpc', (['query'], {}), '(query)\n', (1615, 1622), False, 'from resources.lib.modules import control\n'), ((2155, 2177), 'resources.lib.modules.control.jsonrpc', 'control.jsonrpc', (['query'], {}), '(query)\n', (2170, 2177), False, 'from resources.lib.modules import control\n'), ((2190, 2238), 'resources.lib.modules.control.log', 'control.log', (["('%s restored to %s' % (item, value))"], {}), "('%s restored to %s' % (item, value))\n", (2201, 2238), False, 'from resources.lib.modules import control\n'), ((2694, 2761), 're.compile', 're.compile', (['"""<lookandfeel>.+?<ski.+?>(.+?)</skin>.+?</lookandfeel>"""'], {}), "('<lookandfeel>.+?<ski.+?>(.+?)</skin>.+?</lookandfeel>')\n", (2704, 2761), False, 'import os, re, shutil, time, xbmc\n'), ((4029, 4062), 'os.path.join', 'os.path.join', (['ADDONS', 'DEFAULTSKIN'], {}), '(ADDONS, DEFAULTSKIN)\n', (4041, 4062), False, 'import os, re, shutil, time, xbmc\n'), ((4532, 4569), 'resources.lib.modules.control.setSetting', 'control.setSetting', (['"""defaultskin"""', '""""""'], {}), "('defaultskin', '')\n", (4550, 4569), False, 'from resources.lib.modules import control\n'), ((4571, 4612), 'resources.lib.modules.control.setSetting', 'control.setSetting', (['"""defaultskinname"""', '""""""'], {}), "('defaultskinname', '')\n", (4589, 4612), False, 'from resources.lib.modules import control\n'), ((4751, 4782), 'os.path.join', 'os.path.join', (['ADDONS', '"""skin.*/"""'], {}), "(ADDONS, 'skin.*/')\n", (4763, 4782), False, 'import os, re, shutil, time, xbmc\n'), ((4842, 4861), 'os.path.exists', 'os.path.exists', (['xml'], {}), '(xml)\n', (4856, 4861), False, 'import os, re, shutil, time, xbmc\n'), ((6586, 6634), 'resources.lib.modules.control.loga', 'control.loga', (['"""No skins found in addons folder."""'], {}), "('No skins found in addons folder.')\n", (6598, 6634), False, 'from resources.lib.modules import control\n'), ((6636, 6683), 'resources.lib.modules.control.setSetting', 'control.setSetting', (['"""defaultskinignore"""', '"""true"""'], {}), "('defaultskinignore', 'true')\n", (6654, 6683), False, 'from resources.lib.modules import control\n'), ((6907, 6925), 'resources.lib.modules.control.sleep', 'control.sleep', (['(200)'], {}), '(200)\n', (6920, 6925), False, 'from resources.lib.modules import control\n'), ((7006, 7038), 'resources.lib.modules.control.execute', 'control.execute', (['"""SendClick(11)"""'], {}), "('SendClick(11)')\n", (7021, 7038), False, 'from resources.lib.modules import control\n'), ((7092, 7150), 'resources.lib.modules.control.Notify', 'control.Notify', (['control.AddonTitle', '"""Skin Swap Timed Out!"""'], {}), "(control.AddonTitle, 'Skin Swap Timed Out!')\n", (7106, 7150), False, 'from resources.lib.modules import control\n'), ((1841, 1889), 'resources.lib.modules.control.log', 'control.log', (["('%s saved to %s' % (item, match[0]))"], {}), "('%s saved to %s' % (item, match[0]))\n", (1852, 1889), False, 'from resources.lib.modules import control\n'), ((4416, 4450), 'resources.lib.modules.control.loga', 'control.loga', (['"""Skin was not reset"""'], {}), "('Skin was not reset')\n", (4428, 4450), False, 'from resources.lib.modules import control\n'), ((4452, 4499), 'resources.lib.modules.control.setSetting', 'control.setSetting', (['"""defaultskinignore"""', '"""true"""'], {}), "('defaultskinignore', 'true')\n", (4470, 4499), False, 'from resources.lib.modules import control\n'), ((5378, 5422), 'resources.lib.modules.control.loga', 'control.loga', (["('ID not found for %s' % folder)"], {}), "('ID not found for %s' % folder)\n", (5390, 5422), False, 'from resources.lib.modules import control\n'), ((6807, 6862), 'resources.lib.modules.control.condVisibility', 'control.condVisibility', (['"""Window.isVisible(yesnodialog)"""'], {}), "('Window.isVisible(yesnodialog)')\n", (6829, 6862), False, 'from resources.lib.modules import control\n'), ((3125, 3163), 're.compile', 're.compile', (['"""<addon.+?ame="(.+?)".+?>"""'], {}), '(\'<addon.+?ame="(.+?)".+?>\')\n', (3135, 3163), False, 'import os, re, shutil, time, xbmc\n'), ((5315, 5359), 'resources.lib.modules.control.loga', 'control.loga', (["('ID not found for %s' % folder)"], {}), "('ID not found for %s' % folder)\n", (5327, 5359), False, 'from resources.lib.modules import control\n'), ((6072, 6106), 'resources.lib.modules.control.loga', 'control.loga', (['"""Skin was not reset"""'], {}), "('Skin was not reset')\n", (6084, 6106), False, 'from resources.lib.modules import control\n'), ((6108, 6155), 'resources.lib.modules.control.setSetting', 'control.setSetting', (['"""defaultskinignore"""', '"""true"""'], {}), "('defaultskinignore', 'true')\n", (6126, 6155), False, 'from resources.lib.modules import control\n'), ((6488, 6522), 'resources.lib.modules.control.loga', 'control.loga', (['"""Skin was not reset"""'], {}), "('Skin was not reset')\n", (6500, 6522), False, 'from resources.lib.modules import control\n'), ((6524, 6571), 'resources.lib.modules.control.setSetting', 'control.setSetting', (['"""defaultskinignore"""', '"""true"""'], {}), "('defaultskinignore', 'true')\n", (6542, 6571), False, 'from resources.lib.modules import control\n'), ((1687, 1716), 're.compile', 're.compile', (['"""{"value":(.+?)}"""'], {}), '(\'{"value":(.+?)}\')\n', (1697, 1716), False, 'import os, re, shutil, time, xbmc\n'), ((5004, 5041), 're.compile', 're.compile', (['"""<addon.+?id="(.+?)".+?>"""'], {}), '(\'<addon.+?id="(.+?)".+?>\')\n', (5014, 5041), False, 'import os, re, shutil, time, xbmc\n'), ((5078, 5117), 're.compile', 're.compile', (['"""<addon.+?name="(.+?)".+?>"""'], {}), '(\'<addon.+?name="(.+?)".+?>\')\n', (5088, 5117), False, 'import os, re, shutil, time, xbmc\n'), ((5835, 5869), 'resources.lib.modules.control.loga', 'control.loga', (['"""Skin was not reset"""'], {}), "('Skin was not reset')\n", (5847, 5869), False, 'from resources.lib.modules import control\n'), ((5871, 5918), 'resources.lib.modules.control.setSetting', 'control.setSetting', (['"""defaultskinignore"""', '"""true"""'], {}), "('defaultskinignore', 'true')\n", (5889, 5918), False, 'from resources.lib.modules import control\n')]