# -*- 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")



[((9, 9, 9, 49), 'os.path.join', 'os.path.join', ({(9, 22, 9, 38): 'control.HOMEPATH', (9, 40, 9, 48): '"""addons"""'}, {}), "(control.HOMEPATH, 'addons')", False, 'import os, re, shutil, time, xbmc\n'), ((68, 4, 68, 39), 'resources.lib.modules.control.log', 'control.log', ({(68, 16, 68, 38): '"""[Default Skin Check]"""'}, {}), "('[Default Skin Check]')", False, 'from resources.lib.modules import control\n'), ((69, 14, 69, 55), 'os.path.join', 'os.path.join', ({(69, 27, 69, 39): 'USERDATAPATH', (69, 41, 69, 54): '"""guitemp.xml"""'}, {}), "(USERDATAPATH, 'guitemp.xml')", False, 'import os, re, shutil, time, xbmc\n'), ((72, 4, 72, 45), 'resources.lib.modules.control.log', 'control.log', ({(72, 16, 72, 44): "('Reading gui file: %s' % gui)"}, {}), "('Reading gui file: %s' % gui)", False, 'from resources.lib.modules import control\n'), ((75, 4, 75, 39), 'resources.lib.modules.control.log', 'control.log', ({(75, 16, 75, 38): '"""Opening gui settings"""'}, {}), "('Opening gui settings')", False, 'from resources.lib.modules import control\n'), ((93, 7, 93, 30), 'os.path.exists', 'os.path.exists', ({(93, 22, 93, 29): 'tempgui'}, {}), '(tempgui)', False, 'import os, re, shutil, time, xbmc\n'), ((96, 4, 96, 43), 'resources.lib.modules.control.log', 'control.log', ({(96, 16, 96, 42): '"""[Default Skin Check] End"""'}, {}), "('[Default Skin Check] End')", False, 'from resources.lib.modules import control\n'), ((100, 4, 100, 44), 'resources.lib.modules.control.loga', 'control.loga', ({(100, 17, 100, 43): '"""Invalid Skin Check Start"""'}, {}), "('Invalid Skin Check Start')", False, 'from resources.lib.modules import control\n'), ((151, 4, 151, 42), 'resources.lib.modules.control.loga', 'control.loga', ({(151, 17, 151, 41): '"""Invalid Skin Check End"""'}, {}), "('Invalid Skin Check End')", False, 'from resources.lib.modules import control\n'), ((20, 19, 20, 41), 'resources.lib.modules.control.jsonrpc', 'control.jsonrpc', ({(20, 35, 20, 40): 'query'}, {}), '(query)', False, 'from resources.lib.modules import control\n'), ((21, 19, 21, 45), 'simplejson.loads', 'simplejson.loads', ({(21, 36, 21, 44): 'response'}, {}), '(response)', False, 'import simplejson\n'), ((35, 19, 35, 41), 'resources.lib.modules.control.jsonrpc', 'control.jsonrpc', ({(35, 35, 35, 40): 'query'}, {}), '(query)', False, 'from resources.lib.modules import control\n'), ((70, 21, 70, 44), 'os.path.exists', 'os.path.exists', ({(70, 36, 70, 43): 'tempgui'}, {}), '(tempgui)', False, 'import os, re, shutil, time, xbmc\n'), ((71, 11, 71, 30), 'os.path.exists', 'os.path.exists', ({(71, 26, 71, 29): 'gui'}, {}), '(gui)', False, 'import os, re, shutil, time, xbmc\n'), ((80, 19, 80, 62), 'os.path.join', 'os.path.join', ({(80, 32, 80, 38): 'ADDONS', (80, 40, 80, 48): 'match[0]', (80, 50, 80, 61): '"""addon.xml"""'}, {}), "(ADDONS, match[0], 'addon.xml')", False, 'import os, re, shutil, time, xbmc\n'), ((81, 11, 81, 35), 'os.path.exists', 'os.path.exists', ({(81, 26, 81, 34): 'addonxml'}, {}), '(addonxml)', False, 'import os, re, shutil, time, xbmc\n'), ((88, 8, 88, 68), 'resources.lib.modules.control.log', 'control.log', ({(88, 20, 88, 67): "('[Default Skin Check] Skin name: %s' % skinname)"}, {}), "('[Default Skin Check] Skin name: %s' % skinname)", False, 'from resources.lib.modules import control\n'), ((89, 8, 89, 64), 'resources.lib.modules.control.log', 'control.log', ({(89, 20, 89, 63): "('[Default Skin Check] Skin id: %s' % skinid)"}, {}), "('[Default Skin Check] Skin id: %s' % skinid)", False, 'from resources.lib.modules import control\n'), ((90, 8, 90, 49), 'resources.lib.modules.control.setSetting', 'control.setSetting', ({(90, 27, 90, 40): '"""defaultskin"""', (90, 42, 90, 48): 'skinid'}, {}), "('defaultskin', skinid)", False, 'from resources.lib.modules import control\n'), ((91, 8, 91, 55), 'resources.lib.modules.control.setSetting', 'control.setSetting', ({(91, 27, 91, 44): '"""defaultskinname"""', (91, 46, 91, 54): 'skinname'}, {}), "('defaultskinname', skinname)", False, 'from resources.lib.modules import control\n'), ((92, 8, 92, 56), 'resources.lib.modules.control.setSetting', 'control.setSetting', ({(92, 27, 92, 46): '"""defaultskinignore"""', (92, 48, 92, 55): '"""false"""'}, {}), "('defaultskinignore', 'false')", False, 'from resources.lib.modules import control\n'), ((94, 8, 94, 46), 'resources.lib.modules.control.log', 'control.log', ({(94, 20, 94, 45): '"""Deleting Temp Gui File."""'}, {}), "('Deleting Temp Gui File.')", False, 'from resources.lib.modules import control\n'), ((95, 8, 95, 26), 'os.remove', 'os.remove', ({(95, 18, 95, 25): 'tempgui'}, {}), '(tempgui)', False, 'import os, re, shutil, time, xbmc\n'), ((143, 8, 143, 27), 'resources.lib.modules.control.sleep', 'control.sleep', ({(143, 22, 143, 26): '(1000)'}, {}), '(1000)', False, 'from resources.lib.modules import control\n'), ((147, 11, 147, 66), 'resources.lib.modules.control.condVisibility', 'control.condVisibility', ({(147, 34, 147, 65): '"""Window.isVisible(yesnodialog)"""'}, {}), "('Window.isVisible(yesnodialog)')", False, 'from resources.lib.modules import control\n'), ((54, 23, 54, 45), 'resources.lib.modules.control.jsonrpc', 'control.jsonrpc', ({(54, 39, 54, 44): 'query'}, {}), '(query)', False, 'from resources.lib.modules import control\n'), ((63, 23, 63, 45), 'resources.lib.modules.control.jsonrpc', 'control.jsonrpc', ({(63, 39, 63, 44): 'query'}, {}), '(query)', False, 'from resources.lib.modules import control\n'), ((64, 12, 64, 60), 'resources.lib.modules.control.log', 'control.log', ({(64, 24, 64, 59): "('%s restored to %s' % (item, value))"}, {}), "('%s restored to %s' % (item, value))", False, 'from resources.lib.modules import control\n'), ((76, 12, 76, 79), 're.compile', 're.compile', ({(76, 23, 76, 78): '"""<lookandfeel>.+?<ski.+?>(.+?)</skin>.+?</lookandfeel>"""'}, {}), "('<lookandfeel>.+?<ski.+?>(.+?)</skin>.+?</lookandfeel>')", False, 'import os, re, shutil, time, xbmc\n'), ((106, 26, 106, 59), 'os.path.join', 'os.path.join', ({(106, 39, 106, 45): 'ADDONS', (106, 47, 106, 58): 'DEFAULTSKIN'}, {}), '(ADDONS, DEFAULTSKIN)', False, 'import os, re, shutil, time, xbmc\n'), ((111, 14, 111, 51), 'resources.lib.modules.control.setSetting', 'control.setSetting', ({(111, 33, 111, 46): '"""defaultskin"""', (111, 48, 111, 50): '""""""'}, {}), "('defaultskin', '')", False, 'from resources.lib.modules import control\n'), ((111, 53, 111, 94), 'resources.lib.modules.control.setSetting', 'control.setSetting', ({(111, 72, 111, 89): '"""defaultskinname"""', (111, 91, 111, 93): '""""""'}, {}), "('defaultskinname', '')", False, 'from resources.lib.modules import control\n'), ((115, 32, 115, 63), 'os.path.join', 'os.path.join', ({(115, 45, 115, 51): 'ADDONS', (115, 53, 115, 62): '"""skin.*/"""'}, {}), "(ADDONS, 'skin.*/')", False, 'import os, re, shutil, time, xbmc\n'), ((117, 15, 117, 34), 'os.path.exists', 'os.path.exists', ({(117, 30, 117, 33): 'xml'}, {}), '(xml)', False, 'import os, re, shutil, time, xbmc\n'), ((139, 14, 139, 62), 'resources.lib.modules.control.loga', 'control.loga', ({(139, 27, 139, 61): '"""No skins found in addons folder."""'}, {}), "('No skins found in addons folder.')", False, 'from resources.lib.modules import control\n'), ((139, 64, 139, 111), 'resources.lib.modules.control.setSetting', 'control.setSetting', ({(139, 83, 139, 102): '"""defaultskinignore"""', (139, 104, 139, 110): '"""true"""'}, {}), "('defaultskinignore', 'true')", False, 'from resources.lib.modules import control\n'), ((146, 12, 146, 30), 'resources.lib.modules.control.sleep', 'control.sleep', ({(146, 26, 146, 29): '(200)'}, {}), '(200)', False, 'from resources.lib.modules import control\n'), ((148, 12, 148, 44), 'resources.lib.modules.control.execute', 'control.execute', ({(148, 28, 148, 43): '"""SendClick(11)"""'}, {}), "('SendClick(11)')", False, 'from resources.lib.modules import control\n'), ((150, 14, 150, 71), 'resources.lib.modules.control.Notify', 'control.Notify', ({(150, 29, 150, 47): 'control.AddonTitle', (150, 48, 150, 70): '"""Skin Swap Timed Out!"""'}, {}), "(control.AddonTitle, 'Skin Swap Timed Out!')", False, 'from resources.lib.modules import control\n'), ((58, 16, 58, 64), 'resources.lib.modules.control.log', 'control.log', ({(58, 28, 58, 63): "('%s saved to %s' % (item, match[0]))"}, {}), "('%s saved to %s' % (item, match[0]))", False, 'from resources.lib.modules import control\n'), ((110, 18, 110, 52), 'resources.lib.modules.control.loga', 'control.loga', ({(110, 31, 110, 51): '"""Skin was not reset"""'}, {}), "('Skin was not reset')", False, 'from resources.lib.modules import control\n'), ((110, 54, 110, 101), 'resources.lib.modules.control.setSetting', 'control.setSetting', ({(110, 73, 110, 92): '"""defaultskinignore"""', (110, 94, 110, 100): '"""true"""'}, {}), "('defaultskinignore', 'true')", False, 'from resources.lib.modules import control\n'), ((124, 18, 124, 62), 'resources.lib.modules.control.loga', 'control.loga', ({(124, 31, 124, 61): "('ID not found for %s' % folder)"}, {}), "('ID not found for %s' % folder)", False, 'from resources.lib.modules import control\n'), ((144, 18, 144, 73), 'resources.lib.modules.control.condVisibility', 'control.condVisibility', ({(144, 41, 144, 72): '"""Window.isVisible(yesnodialog)"""'}, {}), "('Window.isVisible(yesnodialog)')", False, 'from resources.lib.modules import control\n'), ((84, 21, 84, 59), 're.compile', 're.compile', ({(84, 32, 84, 58): '"""<addon.+?ame="(.+?)".+?>"""'}, {}), '(\'<addon.+?ame="(.+?)".+?>\')', False, 'import os, re, shutil, time, xbmc\n'), ((123, 22, 123, 66), 'resources.lib.modules.control.loga', 'control.loga', ({(123, 35, 123, 65): "('ID not found for %s' % folder)"}, {}), "('ID not found for %s' % folder)", False, 'from resources.lib.modules import control\n'), ((133, 22, 133, 56), 'resources.lib.modules.control.loga', 'control.loga', ({(133, 35, 133, 55): '"""Skin was not reset"""'}, {}), "('Skin was not reset')", False, 'from resources.lib.modules import control\n'), ((133, 58, 133, 105), 'resources.lib.modules.control.setSetting', 'control.setSetting', ({(133, 77, 133, 96): '"""defaultskinignore"""', (133, 98, 133, 104): '"""true"""'}, {}), "('defaultskinignore', 'true')", False, 'from resources.lib.modules import control\n'), ((138, 22, 138, 56), 'resources.lib.modules.control.loga', 'control.loga', ({(138, 35, 138, 55): '"""Skin was not reset"""'}, {}), "('Skin was not reset')", False, 'from resources.lib.modules import control\n'), ((138, 58, 138, 105), 'resources.lib.modules.control.setSetting', 'control.setSetting', ({(138, 77, 138, 96): '"""defaultskinignore"""', (138, 98, 138, 104): '"""true"""'}, {}), "('defaultskinignore', 'true')", False, 'from resources.lib.modules import control\n'), ((56, 24, 56, 53), 're.compile', 're.compile', ({(56, 35, 56, 52): '"""{"value":(.+?)}"""'}, {}), '(\'{"value":(.+?)}\')', False, 'import os, re, shutil, time, xbmc\n'), ((119, 24, 119, 61), 're.compile', 're.compile', ({(119, 35, 119, 60): '"""<addon.+?id="(.+?)".+?>"""'}, {}), '(\'<addon.+?id="(.+?)".+?>\')', False, 'import os, re, shutil, time, xbmc\n'), ((120, 25, 120, 64), 're.compile', 're.compile', ({(120, 36, 120, 63): '"""<addon.+?name="(.+?)".+?>"""'}, {}), '(\'<addon.+?name="(.+?)".+?>\')', False, 'import os, re, shutil, time, xbmc\n'), ((129, 37, 129, 71), 'resources.lib.modules.control.loga', 'control.loga', ({(129, 50, 129, 70): '"""Skin was not reset"""'}, {}), "('Skin was not reset')", False, 'from resources.lib.modules import control\n'), ((129, 73, 129, 120), 'resources.lib.modules.control.setSetting', 'control.setSetting', ({(129, 92, 129, 111): '"""defaultskinignore"""', (129, 113, 129, 119): '"""true"""'}, {}), "('defaultskinignore', 'true')", False, 'from resources.lib.modules import control\n')]