import os
import xbmc
import xbmcaddon
import urllib
import shutil
import time
from xbmcgui import Dialog, DialogProgressBG, DialogProgress
from koding import route, Add_Dir, Addon_Info, Custom_Dialog as cd, Installed_Addons, dolog, Check_Repo, Text_Box, Select_Dialog
from commonfunc import Log, file_reader, xbmcPaths as Path, TextBoxes, TextBoxes2, url_exists, compare_file_timestamps, get_zip_nodp, surfs_enabler, isAddonInstalled, addonSettingChanger
from commonfunc import timestamp2Readable, killSlideShow, dis_or_enable_addon, quitXBMC, listRandomiser, get_zip_silent, Get_OGMC, create_ver_file, get_zip
from build_auto_updater import ogb_checker
from url import getURL

dialog = Dialog()
dpbg = DialogProgressBG()
dp = DialogProgress()

addonID = Addon_Info(id='id')
id_OGT = 'plugin.program.ogtools'
ADDON = xbmcaddon.Addon(addonID)


HOME = Path("home")
ADDONS = Path("addons")
USERDATA = Path("userdata")
MEDIA = os.path.join(HOME, "media/")
SYSTEM = os.path.join(HOME, "system/")
CACHE = os.path.join(HOME, "cache/")
ADDON_DATA = Path("addon_data")
BACKGROUNDS = Path("wallpaper")
KEYMAPS = Path("keymaps")
LIBRARY = Path("lib")
PERIF = Path("peripherals")
PLAYLISTS = Path("plists")
THUMBS = Path("thumbs")
OGT_DIR = Path("ogt")
OGT_DATA = Path("ogtdata")
OGT_ARTdir = Path("ogtart")

HEADING = "[COLORlimegreen]OptimusGREEN Tools[/COLOR]"
OSTitle = "[COLORlimegreen]O[/COLOR]pti[COLORlimegreen]S[/COLOR]ync"

################################################################################
################################################################################
#####                        Welcome Message                               #####
################################################################################
################################################################################


@route(mode="welcome_MSG")
def welcomeMessage():
    filePath = os.path.join(ADDON_DATA, id_OGT, "welcome.txt")
    if not os.path.exists(filePath):
        if isTOGBinstalled():
            Log("##### WELCOME TO THE OPTIMUSGREEN BUILD #####")
            url = getURL("build", "welcome")
            urllib.urlretrieve(url, filePath)
            fileText = file_reader(filePath)
            time.sleep(45)
            TextBoxes2("[COLORlimegreen]The OptimusGREEN Build[/COLOR]", fileText)


################################################################################
################################################################################
#####                               RSS                                    #####
################################################################################
################################################################################


def rss_update_check():
    remoteRSS = getURL("build", "rss")
    localRSS = xbmc.translatePath("special://home/userdata/RssFeeds.xml")
    if url_exists(remoteRSS):
        if os.path.exists(localRSS):
            if compare_file_timestamps(remoteRSS, localRSS):
                Log("################# RSS file has changed.... Downloading #####################")
                urllib.urlretrieve(remoteRSS, localRSS)
            else:
                Log("################# RSS file doesn't need updated #####################")
        else:
            urllib.urlretrieve(remoteRSS, localRSS)
            Log("################# RSS file has changed.... Downloading #####################")

################################################################################
################################################################################
#####                              FIX ITEMS                               #####
################################################################################
################################################################################


@route(mode='run_GETDEPS')
def getBuildDeps():
    if dialog.yesno(HEADING, "Get all build dependencies?", " ", ""):
        url = getURL("build", "deps")
        dpbg.create("[COLORlimegreen]Dependency Fix[/COLOR]")
        if url_exists(url):
            get_zip('ogbuild_deps', url, ADDONS)
            surfs_enabler(dprog="false")
            dpbg.close()
            dialog.ok("[COLORlimegreen]OptimusGREEN Tools[/COLOR]", "Dependencies Installed", "Hopefully you should be good to go!", "The app will now close for changes to take effect.\n This can take several seconds.")
            quitXBMC(forceClose=False, silent=True)
        else:
            dpbg.close()
            dialog.ok("[COLORlimegreen]OptimusGREEN Tools[/COLOR]", "Unable to connect to the remote file., \nPlease try again later.")


@route(mode='run_FIX_VER_FILE')
def runVerFileFix():
    create_ver_file()
    recheckforupdates = dialog.yesno("[COLORlimegreen]Auto Build Updater[/COLOR]", "Your installed Build Version file is now created.", " ", "Do you want to check for updates now??", "No", "Yes")
    if recheckforupdates:
        ogb_checker(getURL("build", "main1"), getURL("build", "main2"))
    else:
        pass


@route(mode="getBuildRepos")
def getBuildRepos():
    url = getURL("build", "repos")
    if dialog.yesno(HEADING, "Are you sure you want to download all the standard repos?"):
        get_zip_nodp("OGBrepos.zip", url, ADDONS)
        xbmc.sleep(1000)
        surfs_enabler(silent=True)
        dialog.ok(HEADING, "Complete!")


@route(mode='run_API_CHANGER')
def API_CHANGER():
    trans = 100
    bgColour = '363636'
    btnColour = '444444'
    # btnColourFocussed = '7A7A7A'
    btnColourFocussed = "228500"
    # Addon ID's
    YT_addonID = "plugin.video.youtube"
    MQ_addonID = "plugin.video.metalliq"
    EL_addonID = "plugin.video.elysium"
    # YouTube
    YT_default_api = "youtube.api.key.switch"
    YT_default_api_list = ["12310", "12311", "12312", "12313", "12314", "12315"]
    YT_enable_api = "youtube.api.enable"
    YT_set_api = "youtube.api.id"
    YT_set_key = "youtube.api.key"
    YT_set_sec = "youtube.api.secret"
    YT_apiID = "173081852393-pvs4lhtqaq8tfk0agre5kqu306cmeqte"
    YT_apiKey = "AIzaSyDwEJd64T5rPm6WeJK8--J2Ot4BFW1Bpi0"
    YT_apiSecret = "H0oMHQl3sHTbOpiAkXtr67UG"
    # TMDb TVDb
    TMDb_OGMC_API = "8bd82d9a9498b5c05daa33d034eb07fa"
    TVDb_OGMC_API = "1DC3EA33331B1781"
    header = "OptimusGREEN Tools API Changer"
    txt_addon = 'Please select the add-on you would like to change an API for.\n\nChanging an API can solve problems with errors due to too much use of an existing API.'
    btns_addons = []
    if isAddonInstalled(YT_addonID):
        btns_addons.append('YouTube')
        currentYT_API_USED = xbmcaddon.Addon(YT_addonID).getSetting(YT_enable_api)
        currentYT_API_VER_USED = xbmcaddon.Addon(YT_addonID).getSetting(YT_default_api)
        currentYT_API = xbmcaddon.Addon(YT_addonID).getSetting(YT_set_api)
        # currentYT_KEY = xbmcaddon.Addon(YT_addonID).getSetting(YT_set_key)
        # currentYT_SEC = xbmcaddon.Addon(YT_addonID).getSetting(YT_set_sec)
        if currentYT_API_USED == 'true' and currentYT_API == YT_apiID:
            currentYT_API = "OGMC API"
        elif currentYT_API_USED == 'true' and not currentYT_API == YT_apiID:
            currentYT_API = "CUSTOM API"
        elif currentYT_API_USED == 'false':
            currentYT_API = "Default API %s" % (currentYT_API_VER_USED)
    if isAddonInstalled(MQ_addonID):
        btns_addons.append('MetalliQ')
        currentMQ_TMDb = xbmcaddon.Addon(MQ_addonID).getSetting("tmdb_api")
        currentMQ_TVDb = xbmcaddon.Addon(MQ_addonID).getSetting("tvdb_api")
        if currentMQ_TMDb == TMDb_OGMC_API:
            currentMQ_TMDb = "OGMC API"
        else:
            currentMQ_TMDb = "Default API"

        if currentMQ_TVDb == TVDb_OGMC_API:
            currentMQ_TVDb = "OGMC API"
        else:
            currentMQ_TVDb = "Default API"
    if isAddonInstalled(EL_addonID):
        btns_addons.append('Elysium')
        currentEL_TMDb = xbmcaddon.Addon(EL_addonID).getSetting("tmdb_apikey")
        # currentEL_TVDb = xbmcaddon.Addon(EL_addonID).getSetting("tvdb_api")
        if currentEL_TMDb == TMDb_OGMC_API:
            currentEL_TMDb = "OGMC API"
        else:
            currentEL_TMDb = "Default API"

        # if currentEL_TVDb == TVDb_OGMC_API:
        #     currentEL_TVDb = "OGMC API"
        # else:
        #     currentEL_TVDb = "Default API"

    txt_Service = "Please select the API you would like to change"
    txt_API = 'Please select an API to use.'
    txt_complete = 'Your API is now set to '
    addon_choice = cd(header=header, pos='center', main_content=txt_addon, buttons=btns_addons, background=bgColour, transparency=trans,
                      highlight_color='gold', button_color_focused=btnColourFocussed, button_trans_focused=trans,
                      button_color_nonfocused=btnColour, button_trans_nonfocused=trans)
    Log("########## ##########    API CHANGER: Addon choice is %s   ########## ##############" % (addon_choice))
    api_type = btns_addons[addon_choice]
    if addon_choice >= 0:
        pass
    else:
        return -1

    # YouTube
    if api_type == 'YouTube':
        currentAPI_txt = '\n\nAPI currently in use is [COLORgold]%s[/COLOR]' % (currentYT_API)
        btns_API = ['Default API', 'OGMC API']
        btns_API_VERSION = YT_default_api_list
        API_Choice = cd(header=header, pos='center', main_content=txt_API + currentAPI_txt, buttons=btns_API, background=bgColour, transparency=trans,
                        highlight_color='gold', button_color_focused=btnColourFocussed, button_trans_focused=trans,
                        button_color_nonfocused=btnColour, button_trans_nonfocused=trans)
        chosenAPI = btns_API[API_Choice]
        if API_Choice >= 0:
            pass
        else:
            return -1
        # Default API
        if chosenAPI == 'Default API':
            API_VERS_CHOICE = cd(header=header, pos='center', main_content=txt_API + currentAPI_txt + "\n\nChoose which version of the default API to use", buttons=YT_default_api_list, background=bgColour, transparency=trans,
                                 highlight_color='gold', button_color_focused=btnColourFocussed, button_trans_focused=trans,
                                 button_color_nonfocused=btnColour, button_trans_nonfocused=trans)
            chosenAPIVERS = btns_API_VERSION[API_VERS_CHOICE]
            if API_VERS_CHOICE >= 0:
                pass
            else:
                return -1
            if chosenAPIVERS == '12310':
                newChosenAPIVERS = '0'
            elif chosenAPIVERS == '12311':
                newChosenAPIVERS = '1'
            elif chosenAPIVERS == '12312':
                newChosenAPIVERS = '2'
            elif chosenAPIVERS == '12313':
                newChosenAPIVERS = '3'
            elif chosenAPIVERS == '12314':
                newChosenAPIVERS = '4'
            elif chosenAPIVERS == '12315':
                newChosenAPIVERS = '5'
            addonSettingChanger(addonID=YT_addonID, settingID=YT_enable_api, newValue='false', silent=True)
            addonSettingChanger(addonID=YT_addonID, settingID=YT_default_api, newValue=newChosenAPIVERS, silent=True)
            # addonSettingChanger(addonID=YT_addonID, settingID=YT_default_api, newValue=random.choice(YT_default_api_list), silent=True)
            addonSettingChanger(addonID=YT_addonID, settingID=YT_set_api, newValue='', silent=True)
            addonSettingChanger(addonID=YT_addonID, settingID=YT_set_key, newValue='', silent=True)
            addonSettingChanger(addonID=YT_addonID, settingID=YT_set_sec, newValue='', silent=True)
            cd(header=header, pos='center', main_content=txt_complete + '[COLORgold]Default API %s[/COLOR]' % (xbmcaddon.Addon(YT_addonID).getSetting(YT_default_api)), buttons=["OK"], background=bgColour, transparency=trans,
               highlight_color='gold', button_color_focused=btnColourFocussed, button_trans_focused=trans,
               button_color_nonfocused=btnColour, button_trans_nonfocused=trans)
        # OGMC API
        elif chosenAPI == 'OGMC API':
            addonSettingChanger(addonID=YT_addonID, settingID=YT_enable_api, newValue='true', silent=True)
            addonSettingChanger(addonID=YT_addonID, settingID=YT_set_api, newValue=YT_apiID, silent=True)
            addonSettingChanger(addonID=YT_addonID, settingID=YT_set_key, newValue=YT_apiKey, silent=True)
            addonSettingChanger(addonID=YT_addonID, settingID=YT_set_sec, newValue=YT_apiSecret, silent=True)
            cd(header=header, pos='center', main_content=txt_complete + '[COLORgold]OGMC API[/COLOR]', buttons=["OK"], background=bgColour, transparency=trans,
               highlight_color='gold', button_color_focused=btnColourFocussed, button_trans_focused=trans,
               button_color_nonfocused=btnColour, button_trans_nonfocused=trans)
    # Metalliq
    elif api_type == "MetalliQ":
        btns_Service = ['TMDb', 'TVDb']
        Service_Choice = cd(header=header, pos='center', main_content=txt_Service, buttons=btns_Service, background=bgColour, transparency=trans,
                            highlight_color='gold', button_color_focused=btnColourFocussed, button_trans_focused=trans,
                            button_color_nonfocused=btnColour, button_trans_nonfocused=trans)
        chosenSERVICE = btns_Service[Service_Choice]
        if Service_Choice >= 0:
            pass
        else:
            return -1
        # TMDb
        if chosenSERVICE == 'TMDb':
            set_api = "tmdb_api"
            btns_API = ['Default API', 'OGMC API']
            currentAPI_txt = '\n\nAPI currently in use is [COLORgold]%s[/COLOR]' % (currentMQ_TMDb)
            API_Choice = cd(header=header, pos='center', main_content=txt_API + currentAPI_txt, buttons=btns_API, background=bgColour, transparency=trans,
                            highlight_color='gold', button_color_focused=btnColourFocussed, button_trans_focused=trans,
                            button_color_nonfocused=btnColour, button_trans_nonfocused=trans)
            chosenAPI = btns_API[API_Choice]
            if API_Choice >= 0:
                pass
            else:
                return -1
            # Default API
            if API_Choice == 0:
                addonSettingChanger(addonID=MQ_addonID, settingID=set_api, newValue='', silent=True)
                cd(header=header, pos='center', main_content=txt_complete + '[COLORgold]Default API[/COLOR]', buttons=["OK"], background=bgColour, transparency=trans,
                   highlight_color='gold', button_color_focused=btnColourFocussed, button_trans_focused=trans,
                   button_color_nonfocused=btnColour, button_trans_nonfocused=trans)
            elif API_Choice == 1:
                addonSettingChanger(addonID=MQ_addonID, settingID=set_api, newValue=TMDb_OGMC_API, silent=True)
                cd(header=header, pos='center', main_content=txt_complete + '[COLORgold]OGMC API[/COLOR]', buttons=["OK"], background=bgColour, transparency=trans,
                   highlight_color='gold', button_color_focused=btnColourFocussed, button_trans_focused=trans,
                   button_color_nonfocused=btnColour, button_trans_nonfocused=trans)
        # TVDb
        elif chosenSERVICE == 'TVDb':
            set_api = "tvdb_api"
            btns_API = ['Default API', 'OGMC API']
            currentAPI_txt = '\n\nAPI currently in use is [COLORgold]%s[/COLOR]' % (currentMQ_TVDb)
            API_Choice = cd(header=header, pos='center', main_content=txt_API + currentAPI_txt, buttons=btns_API, background=bgColour, transparency=trans,
                            highlight_color='gold', button_color_focused=btnColourFocussed, button_trans_focused=trans,
                            button_color_nonfocused=btnColour, button_trans_nonfocused=trans)
            chosenAPI = btns_API[API_Choice]
            if API_Choice >= 0:
                pass
            else:
                return -1
            # Default API
            if chosenAPI == 'Default API':
                addonSettingChanger(addonID=MQ_addonID, settingID=set_api, newValue='', silent=True)
                cd(header=header, pos='center', main_content=txt_complete + '[COLORgold]Default API[/COLOR]', buttons=["OK"], background=bgColour, transparency=trans,
                   highlight_color='gold', button_color_focused=btnColourFocussed, button_trans_focused=trans,
                   button_color_nonfocused=btnColour, button_trans_nonfocused=trans)
            # OGMC API
            elif chosenAPI == 'OGMC API':
                addonSettingChanger(addonID=MQ_addonID, settingID=set_api, newValue=TVDb_OGMC_API, silent=True)
                cd(header=header, pos='center', main_content=txt_complete + '[COLORgold]OGMC API[/COLOR]', buttons=["OK"], background=bgColour, transparency=trans,
                   highlight_color='gold', button_color_focused=btnColourFocussed, button_trans_focused=trans,
                   button_color_nonfocused=btnColour, button_trans_nonfocused=trans)
    # Elysium
    elif api_type == "Elysium":
        btns_Service = ['TMDb']
        Service_Choice = cd(header=header, pos='center', main_content=txt_Service, buttons=btns_Service, background=bgColour, transparency=trans,
                            highlight_color='gold', button_color_focused=btnColourFocussed, button_trans_focused=trans,
                            button_color_nonfocused=btnColour, button_trans_nonfocused=trans)
        chosenSERVICE = btns_Service[Service_Choice]
        if Service_Choice >= 0:
            pass
        else:
            return -1
        # TMDb
        if chosenSERVICE == 'TMDb':
            set_api = "tmdb_apikey"
            btns_API = ['Default API', 'OGMC API']
            currentAPI_txt = '\n\nAPI currently in use is [COLORgold]%s[/COLOR]' % (currentEL_TMDb)
            API_Choice = cd(header=header, pos='center', main_content=txt_API + currentAPI_txt, buttons=btns_API, background=bgColour, transparency=trans,
                            highlight_color='gold', button_color_focused=btnColourFocussed, button_trans_focused=trans,
                            button_color_nonfocused=btnColour, button_trans_nonfocused=trans)
            chosenAPI = btns_API[API_Choice]
            if API_Choice >= 0:
                pass
            else:
                return -1
            # Default API
            if chosenAPI == 'Default API':
                addonSettingChanger(addonID=EL_addonID, settingID=set_api, newValue='', silent=True)
                cd(header=header, pos='center', main_content=txt_complete + '[COLORgold]Default API[/COLOR]', buttons=["OK"], background=bgColour, transparency=trans,
                   highlight_color='gold', button_color_focused=btnColourFocussed, button_trans_focused=trans,
                   button_color_nonfocused=btnColour, button_trans_nonfocused=trans)
            elif chosenAPI == 'OGMC API':
                addonSettingChanger(addonID=EL_addonID, settingID=set_api, newValue=TMDb_OGMC_API, silent=True)
                cd(header=header, pos='center', main_content=txt_complete + '[COLORgold]OGMC API[/COLOR]', buttons=["OK"], background=bgColour, transparency=trans,
                   highlight_color='gold', button_color_focused=btnColourFocussed, button_trans_focused=trans,
                   button_color_nonfocused=btnColour, button_trans_nonfocused=trans)
        # TVDb
        # elif chosenSERVICE == 1:
        #     set_api = "tvdb_api"
        #     btns_API = ['Default API', 'OGMC API']
        #     currentAPI_txt = '\n\nAPI currently in use is [COLORgold]%s[/COLOR]' % (currentEL_TVDb)
        #     API_Choice = cd(header=header, pos='center', main_content=txt_API, buttons=btns_API, background=bgColour, transparency=trans,\
        #     highlight_color='gold', button_color_focused=btnColourFocussed, button_trans_focused=trans,\
        #     button_color_nonfocused=btnColour, button_trans_nonfocused=trans)
        #     # Default API
        #     if API_Choice == 0:
        #         addonSettingChanger(addonID=EL_addonID, settingID=set_api, newValue='', silent=True)
        #     # OGMC API
        #     elif API_Choice == 1:
        #         addonSettingChanger(addonID=EL_addonID, settingID=set_api, newValue=TVDb_OGMC_API, silent=True)

################################################################################
################################################################################
#####                             Build Quit Menu                          #####
################################################################################
################################################################################


@route(mode="BuildExitOptions", args=["useSelector"])
def BuildExitOptions(useSelector=False):
    from resources.lib.menus.optisync_menu import runOptiSyncAndQuit
    apikey = ADDON.getSetting("dropbox_apikey")
    # osTog = ADDON.getSetting("optisync_toggle")
    if useSelector:
        pass
    else:
        if not apikey == "":
            if dialog.yesno("[COLORlimegreen]Quit Options[/COLOR]", "[COLORlimegreen]QUIT[/COLOR]: Exit Normally", OSTitle + ": Sync and Quit", "", "Quit", "OptiSync Quit"):
                runOptiSyncAndQuit(forceRun=True, dialogOverRide="dp", quit=True)
                return
            else:
                pass
        else:
            pass
        quitXBMC()


################################################################################
################################################################################
#####                             Auto Tasks Schedule                      #####
################################################################################
################################################################################


def showSchedule(tupleName, showName=False):
    # from filetools import xml
    # timeFile = xml(Path("timestamp"))
    # tupleName is a tuple in the form of (name, timestampSettingID, freqSettingID, autoToggleID )
    mastAuto = xbmcaddon.Addon(id_OGT).getSetting("auto_backup")
    name = tupleName[0]
    setID = tupleName[1]
    freqID = tupleName[2]
    # Log("Name: %s - setID: %s - freqID: %s" % (name, setID, freqID))
    auto = xbmcaddon.Addon(id_OGT).getSetting(tupleName[3])
    try:
        prev = timestamp2Readable(timestampSettingID=setID, freqSettingID=freqID)
    except:
        prev = "[COLORred]Not Completed[/COLOR]"
    if mastAuto == 'true' and auto == 'true':
        try:
            nxt = timestamp2Readable(timestampSettingID=setID, freqSettingID=freqID, showNext=True)
            Log("nxt: %s" % (nxt))
        except:
            nxt = "[COLORred]Not Scheduled[/COLOR]"
            Log("in except")
    else:
        nxt = "[COLORred]Not Scheduled[/COLOR]"
    if showName:
        output = "[COLORwhite]%s[/COLOR] - Previous: [COLORspringgreen]%s[/COLOR] - Next: [COLORgold]%s[/COLOR]" % (name, prev, nxt)
    else:
        output = "Previous: [COLORspringgreen]%s[/COLOR] - Next: [COLORgold]%s[/COLOR]" % (prev, nxt)
    # Log("output: %s " % (output))
    return output


@route(mode="listSchedule")
def listSchedule(tupleNameList, showName=True, textBox=True, largeTextBox=False, name=None):
    # tupleNameList is a list of tuples to be passed to showSchedule()
    mylist = []
    if not name:
        name = "Schedule"
    for item in tupleNameList:
        if not textBox:
            if showName:
                Add_Dir(name=showSchedule(item, True), url="", mode='', folder=False, icon="")
            else:
                Add_Dir(name=showSchedule(item, False), url="", mode='', folder=False, icon="")
        else:
            mylist.append(showSchedule(item, True))
    if textBox:
        mystring = '\n\n' + '\n'.join(mylist)
        if largeTextBox:
            TextBoxes("[COLORwhite]%s[/COLOR]" % (name), mystring)
        else:
            TextBoxes2("[COLORwhite]%s[/COLOR]" % (name), mystring)

################################################################################
################################################################################
#####                             Repo Checker                             #####
################################################################################
################################################################################


@route(mode='run_REPO_STATUS')
def build_repo_status():

    repo_list = []
    display_list = []

    dpbg.create("[COLORlimegreen]Checking Repo Status[/COLOR]", "Please Wait...")

    repo_list = Installed_Addons(types='xbmc.addon.repository', properties='path,name')

# Slightly unrelated but I added debug in the settings, if enabled it will print to log with dolog.
# If you edit how your functions are called by using koding.run then you'll also get much better error
# reporting in the actual addon itself (if debug enabled) and any errors without debug enabled will
# be suppressed so user doesn't get the annoying script errors when something goes wrong.

# Removed this, may as well just use the Installed_Addons command which sends back a dictionary
    # for item in os.listdir(ADDONS):
    #     if 'repository' in item:
    #         repo_list.append(item)

    dpbg.close()
    dpbg.create("[COLORlimegreen]Checking Repo Status[/COLOR]")

    list_size = len(repo_list)
    item_percent = 100 / list_size
    percent = 0

    for item in repo_list:
        dolog('repo details: ' + repr(item))
        percent = percent + item_percent
        dpbg.update(percent, "", item['name'])
        if Check_Repo(repo=item['path'], show_busy=False):
            display_list.append('%s' % (item['name'] + ': [COLORlime]ONLINE[/COLOR]'))
        else:
            display_list.append('%s' % (item['name'] + ': [COLORred]OFFLINE[/COLOR]'))

# Not sure if it's an OSX issue or universal but unless you add the isFinished command the dialog never closes
    dpbg.close()
    # if (dpbg.isFinished()):
    #     dpbg.close()

    dialog.select("[COLORgold]Repo Status Checker[/COLOR]", sorted(display_list))


def unmarkTerritory():
    file = os.path.join(HOME, "preInstallerPissStain.txt")
    if not os.path.exists(file):
        Log("#################   OGTOOLS SERVICE: No Piss Stain to remove  ###########################", xbmc.LOGNOTICE)
        pass
    else:
        Log("#################   OGTOOLS SERVICE: Getting SlideShow Zip   ###########################", xbmc.LOGNOTICE)
        getInstallerSlideShow()
        Log("#################   OGTOOLS SERVICE: Removing Piss Stain   ###########################", xbmc.LOGNOTICE)
        os.remove(file)
        Log("#################   OGTOOLS SERVICE: Piss Stain Removed    ###########################", xbmc.LOGNOTICE)
        Log("#################   OGTOOLS SERVICE: xbmc.executebuiltin('Action(Back)')    ###########################", xbmc.LOGNOTICE)
        killSlideShow()
        if '.ogmc' in HOME:
            xbmc.sleep(1)
            xbmc.executebuiltin("ReloadSkin()")


def getInstallerSlideShow():
    name = "slideshow.zip"
    url1 = getURL("art", "slideshow1")
    url2 = getURL("art", "slideshow2")
    url3 = getURL("art", "slideshow3")
    urlList = [url1, url2, url3]
    ranUrl = listRandomiser(urlList)
    extractpath = OGT_ARTdir
    if not os.path.exists(os.path.join(extractpath, "slideshow/")):
        get_zip_silent(name, ranUrl, extractpath)


def listMyAddons(content=None, returnDict=False):
    if not content:
        my_addons = Installed_Addons(types='xbmc.python.pluginsource', properties='name')
    elif content == 'video':
        my_addons = Installed_Addons(types='xbmc.python.pluginsource', content='video', properties='name')
    elif content == 'program':
        my_addons = Installed_Addons(types='xbmc.python.pluginsource', content='executable', properties='name')
    elif content == 'music':
        my_addons = Installed_Addons(types='xbmc.python.pluginsource', content='audio', properties='name')
    elif content == 'image':
        my_addons = Installed_Addons(types='xbmc.python.pluginsource', content='image', properties='name')
    elif content == 'photo':
        my_addons = Installed_Addons(types='xbmc.python.pluginsource', content='image', properties='name')
    elif content == 'picture':
        my_addons = Installed_Addons(types='xbmc.python.pluginsource', content='image', properties='name')
    elif content == 'executable':
        my_addons = Installed_Addons(types='xbmc.python.pluginsource', content='executable', properties='name')
    elif content == 'audio':
        my_addons = Installed_Addons(types='xbmc.python.pluginsource', content='audio', properties='name')
    if not returnDict:
        addonType = content
        final_string = ''
        if not content:
            addonType = "all installed"
        for item in my_addons:
            final_string += 'ID: %s | Name: %s\n' % (item["addonid"], item["name"])
        Text_Box('List of %s add-ons' % (addonType), final_string)
    else:
        addon_dict = {}
        for item in my_addons:
            addon_dict['%s' % (item["name"])] = "%s" % (item["addonid"])
        Log("#####################   Addon Dictionary: %s   #############################" % (addon_dict))
        return addon_dict


def selectInstalledAddon():
    myAddonDict = listMyAddons(content=None, returnDict=True)
    sort_dict = sorted(myAddonDict)
    select = Select_Dialog(title='Select an add-on', options=sort_dict, key=True)
    if select >= 0:
        choice = sort_dict[select]
        chosenID = myAddonDict[choice]
        Log("#####################   Chosen Addon ID: %s   #############################" % (chosenID))
        return chosenID
    else:
        return -1


@route(mode='run_ADDON_RESET')
def addonReset():
    addonID = selectInstalledAddon()
    if addonID >= 0:
        path = os.path.join(ADDON_DATA, addonID)
        if os.path.exists(path):
            try:
                shutil.rmtree(path)
            except:
                pass
            try:
                for item in os.listdir(path):
                    try:
                        os.remove(item)
                    except:
                        pass
            except:
                pass
            dialog.ok(HEADING, "Your addon has been reset", "Your may need to restart the app for changes to take effect.")
        else:
            dialog.ok(HEADING, "Your addon was already running default settings", "If you are having issues, it might be worth while re-installing the addon.")
            Log("#####################   addonReset: Path Doesn't Exist: Path: %s   #############################" % (path))


def isTOGBinstalled():
    ogb_check = xbmc.translatePath("special://home/userdata/ogbversion.xml")
    if os.path.exists(ogb_check):
        return True
    else:
        return False


@route(mode='activate_PVR')
def activatePVR():
    if isTOGBinstalled():
        if 'ogmc' in HOME:
            isAppPVRver = False
            OGMC_PVR_check = xbmc.translatePath("special://xbmc/userdata/version.xml")
            verstxt = file_reader(OGMC_PVR_check)
            if 'PVR' in verstxt:
                isAppPVRver = True
            else:
                isAppPVRver = False
                if dialog.yesno(HEADING, 'This feature only works on the PVR version of OGMC', 'You can install the PVR version via the Install menu in OGTools', 'Alternatively, would you like to install this now?'):
                    Get_OGMC(getURL("ogmc", "ogmcpvr"))

        if isAppPVRver:
            # INSERT REST OF CODE HERE
            if dialog.yesno(HEADING, "If successful, you will have to click OK a few times before restarting the app", "Would you like to continue"):
                count = 0
                while not isAddonInstalled('pvr.iptvsimple'):
                    time.sleep(2)
                    isAddonInstalled('pvr.iptvsimple')
                    count += 1
                    if count == 10:
                        break
                else:
                    dis_or_enable_addon('pvr.iptvsimple', enable="true")
                    time.sleep(2)
                    addonSettingChanger(addonID='pvr.iptvsimple', settingID='m3uUrl', newValue='http://ogtv.ml', silent=True)
                    addonSettingChanger(addonID='pvr.iptvsimple', settingID='epgUrl', newValue='http://ogtvguide.ml', silent=True)
                    addonSettingChanger(addonID='pvr.iptvsimple', settingID='logoBaseUrl', newValue='http://ogtvart.ml', silent=True)
                    addonSettingChanger(addonID='pvr.iptvsimple', settingID='m3uCache', newValue='false', silent=True)
                    dialog.ok(HEADING, "The app now needs to close.", "Please click Ok to close the app")
                    dp.create(HEADING, "Closing app now", "This can take several seconds.", "Please be patient")
                    quitXBMC(forceClose=False, silent=True)
    else:
        dialog.ok(HEADING, 'This feature only works on The OptimusGREEN Build')

# update mq players


@route(mode='updateMQPlayers')
def updateMQPlayers():
    xbmc.executebuiltin("RunPlugin(plugin://plugin.video.metalliq/update_players)")
