# -*- coding: utf-8 -*-

import os,sys,urllib,shutil, json, base64
import xbmcaddon,xbmcplugin,xbmcgui,xbmc
import orphAddon
import videoAddon
import MusicAddon
import DocuAddon
import addonsettings
import HeAddon
import shutil


skin         =  xbmc.getSkinDir()
dp           =  xbmcgui.DialogProgress()
HOME         =  xbmc.translatePath('special://home/')
Config = xbmcaddon.Addon()
dialog = xbmcgui.Dialog()
Progress = xbmcgui.DialogProgress()
jsonSetFont = '{"jsonrpc":"2.0", "method":"Settings.SetSettingValue","params":{"setting":"lookandfeel.font","value":"Arial"}, "id":1}'
EXCLUDES     = ['metadata.artists.universal','pvr.iptvsimple','skin.xonfluence','plugin.video.all_addons_stream','plugin.program.meta_search','superrepo.kodi.isengard.all','skin.confluence','service.xbmc.versioncheck','service.subtitles.torec','service.subtitles.subscenter','service.subtitles.opensubtitles','service.skin.widgets','service.library.data.provider','service.gdrive.3david','script.specto.media','script.randomandlastitems','script.module.xbmcswift2','script.module.urlresolver','script.module.TheYid.common','script.module.t0mm0.common','script.module.six','script.module.singledispatch','script.module.simple.downloader','script.module.routing','script.module.requests','script.module.parsedom','script.module.pyxbmct','script.module.myconnpy','script.module.metahandler','script.module.livestreamer','script.module.liveresolver','script.module.israeliveresolver','script.module.httplib2','script.module.html5lib','script.module.futures','script.module.beautifulsoup4','script.module.beautifulsoup','script.module.autoupdate','script.module.autocompletion','script.globalsearch','script.featherence.service','script.favourites','script.exodus.artwork','script.common.plugin.cache','resource.language.he_il','repository.xbmc-israel','repository.xbmchub','repository.TheWiz','repository.thevibe','repository.shani','repository.podgod','repository.nirepo','repository.mdrepo','repository.merlin','repository.merlin-1.0.1','repository.merlin-1.0.1','repository.kodisenyor','repository.kodil','repository.Goliath','repository.filmkodi.com','repository.featherence','repository.exodus','repository.donatelloandhybrid','repository.abeksis','plugin.video.youtube','plugin.video.wallaNew.video','plugin.video.Vodil','plugin.video.The-Music-Source','plugin.video.supercartoons','plugin.video.specto','plugin.video.salts','plugin.video.reshet.video','plugin.video.phstreams','plugin.video.meta','plugin.video.MakoTV','plugin.video.kodisraelkids','plugin.video.kmusictube','plugin.video.KIDSIL','plugin.video.israelive','plugin.video.iltwenty','plugin.video.iconspire','plugin.video.IBA','plugin.video.hotVOD.video','plugin.video.he-trailers','plugin.video.goodfellas','plugin.video.gdrive','plugin.video.featherence.music','plugin.video.featherence.kids','plugin.video.featherence.docu','plugin.video.f4mTester','plugin.video.exodus','plugin.video.Evolve','plugin.video.documentarytube','plugin.video.DecadoDocs','plugin.video.dandymedia','plugin.video.ccloudtv','plugin.video.Brettus.Documentaries','plugin.video.baby','plugin.video.AlphaMovies','plugin.video.alive.hd','plugin.program.repotools','plugin.audio.merlinradio','plugin.audio.jango','plugin.audio.iba-vod','plugin.audio.100fm','plugin.audio.99fm-playlists','metadata.tvdb.com','metadata.common.musicbrainz.org','metadata.common.imdb.com','metadata.album.universal','plugin.program.senyortools','script.module.addon.common','repository.kodisenyor','plugin.video.thewiz.wall','repository.ToMeRepo','plugin.program.senyorwizard','plugin.program.senyorwizard','context.thewiz.wall','plugin.video.anarchitv']

xbmc.executeJSONRPC(jsonSetFont)


def FRESHSTART():
    if skin!= "skin.confluence":
        dialog.ok('senyor tools[COLOR=white] Wizard[/COLOR] ','נא להחליף לסקין המקורי confluence','לפני ביצוע המחיקה','ובצעו שוב את התהליך')
        xbmc.executebuiltin("ActivateWindow(appearancesettings)")
        return
    else:
        choice2 = xbmcgui.Dialog().yesno("[COLOR=red]האם אתה בטוח?!!![/COLOR]", 'האם להסיר הרחבות ונתוני הרחבות ישנות?', '', 'כל ההרחבות וההגדרות יימחקו לגמרי!', yeslabel='[COLOR=red]כן[/COLOR]',nolabel='[COLOR=green]לא[/COLOR]')
    if choice2 == 0:
        return
    elif choice2 == 1:
        dp.create("senyor[COLOR=white] Wizard[/COLOR]","מוחק הרחבות ישנות",'', 'נא להמתין')
        try:
            for root, dirs, files in os.walk(HOME,topdown=True):
                dirs[:] = [d for d in dirs if d not in EXCLUDES]
                for name in files:
                    try:
                        os.remove(os.path.join(root,name))
                        os.rmdir(os.path.join(root,name))
                    except: pass
                        
                for name in dirs:
                    try: os.rmdir(os.path.join(root,name)); os.rmdir(root)
                    except: pass
        except: pass
    REMOVE_EMPTY_FOLDERS()
    REMOVE_EMPTY_FOLDERS()
    REMOVE_EMPTY_FOLDERS()
    REMOVE_EMPTY_FOLDERS()
    REMOVE_EMPTY_FOLDERS()
    REMOVE_EMPTY_FOLDERS()
    REMOVE_EMPTY_FOLDERS()
    REMOVE_EMPTY_FOLDERS()
    REMOVE_EMPTY_FOLDERS()
    REMOVE_EMPTY_FOLDERS()
    dialog.ok('senyor [COLOR=white] Wizard[/COLOR]','האיפוס הצליח, נא לבצע ריסטרט לקודי כדי שהשינויים יישמרו','','')
    killxbmc()
 
def get_params():
        param=[]
        paramstring=sys.argv[2]
        if len(paramstring)>=2:
                params=sys.argv[2]
                cleanedparams=params.replace('?','')
                if (params[len(params)-1]=='/'):
                        params=params[0:len(params)-2]
                pairsofparams=cleanedparams.split('&')
                param={}
                for i in range(len(pairsofparams)):
                        splitparams={}
                        splitparams=pairsofparams[i].split('=')
                        if (len(splitparams))==2:
                                param[splitparams[0]]=splitparams[1]
                                
        return param	

def REMOVE_EMPTY_FOLDERS():
#initialize the counters
    print"########### Start Removing Empty Folders #########"
    empty_count = 0
    used_count = 0
    for curdir, subdirs, files in os.walk(HOME):
        if len(subdirs) == 0 and len(files) == 0: #check for empty directories. len(files) == 0 may be overkill
            empty_count += 1 #increment empty_count
            os.rmdir(curdir) #delete the directory
            print "successfully removed: "+curdir
        elif len(subdirs) > 0 and len(files) > 0: #check for used directories
            used_count += 1 #increment used_count
		
def killxbmc():
    myplatform = platform()
    print "Platform: " + str(myplatform)
    if myplatform == 'osx': # OSX
        print "############   try osx force close  #################"
        try: os.system('killall -9 XBMC')
        except: pass
        try: os.system('killall -9 Kodi')
        except: pass
        dialog.ok("[COLOR=red][B]WARNING  !!![/COLOR][/B]", "If you\'re seeing this message it means the force close", "was unsuccessful. Please force close XBMC/Kodi [COLOR=lime]DO NOT[/COLOR] exit cleanly via the menu.",'')
    elif myplatform == 'linux': #Linux
        print "############   try linux force close  #################"
        try: os.system('killall XBMC')
        except: pass
        try: os.system('killall Kodi')
        except: pass
        try: os.system('killall -9 xbmc.bin')
        except: pass
        try: os.system('killall -9 kodi.bin')
        except: pass
        dialog.ok("[COLOR=red][B]WARNING  !!![/COLOR][/B]", "If you\'re seeing this message it means the force close", "was unsuccessful. Please force close XBMC/Kodi [COLOR=lime]DO NOT[/COLOR] exit cleanly via the menu.",'')
    elif myplatform == 'android': # Android  
        print "############   try android force close  #################"
        try: os.system('adb shell am force-stop org.xbmc.kodi')
        except: pass
        try: os.system('adb shell am force-stop org.kodi')
        except: pass
        try: os.system('adb shell am force-stop org.xbmc.xbmc')
        except: pass
        try: os.system('adb shell am force-stop org.xbmc')
        except: pass        
        dialog.ok("[COLOR=red][B]אזהרה[/COLOR][/B]", "המערכת זוהתה כסטרימר ", "כדי להשלים את תהליך ההתקנה חובה לנתק חשמל מהמכשיר","[COLOR=red]לא ללחוץ על אישור[/COLOR]")
    elif myplatform == 'windows': # Windows
        print "############   try windows force close  #################"
        try:
            os.system('@ECHO off')
            os.system('tskill XBMC.exe')
        except: pass
        try:
            os.system('@ECHO off')
            os.system('tskill Kodi.exe')
        except: pass
        try:
            os.system('@ECHO off')
            os.system('TASKKILL /im Kodi.exe /f')
        except: pass
        try:
            os.system('@ECHO off')
            os.system('TASKKILL /im XBMC.exe /f')
        except: pass
        dialog.ok("[COLOR=red][B]WARNING  !!![/COLOR][/B]", "If you\'re seeing this message it means the force close", "was unsuccessful. Please force close XBMC/Kodi [COLOR=lime]DO NOT[/COLOR] exit cleanly via the menu.","Use task manager and NOT ALT F4")
    else: #ATV
        print "############   try atv force close  #################"
        try: os.system('killall AppleTV')
        except: pass
        print "############   try raspbmc force close  #################" #OSMC / Raspbmc
        try: os.system('sudo initctl stop kodi')
        except: pass
        try: os.system('sudo initctl stop xbmc')
        except: pass
        dialog.ok("[COLOR=red][B]WARNING  !!![/COLOR][/B]", "If you\'re seeing this message it means the force close", "was unsuccessful. Please force close XBMC/Kodi [COLOR=lime]DO NOT[/COLOR] exit via the menu.","Your platform could not be detected so just pull the power cable.")

def platform():
    if xbmc.getCondVisibility('system.platform.android'):
        return 'android'
    elif xbmc.getCondVisibility('system.platform.linux'):
        return 'linux'
    elif xbmc.getCondVisibility('system.platform.windows'):
        return 'windows'
    elif xbmc.getCondVisibility('system.platform.osx'):
        return 'osx'
    elif xbmc.getCondVisibility('system.platform.atv2'):
        return 'atv2'
    elif xbmc.getCondVisibility('system.platform.ios'):
        return 'ios'		
	
	
Config.openSettings()

if Config.getSetting("deletekodi") == 'true':   
	FRESHSTART()

if Config.getSetting("addonsset") == 'true':
    Progress.create("מתקין הגדרות מומלצות להרחבות...", "נא להמתין...")
    Progress.update(10)
    addonsettings.Exodus_Settings() 	
    Progress.update(20)	
    addonsettings.Salts_Settings()    	
    Progress.update(50)
    addonsettings.Meta_Settings()       	
    Progress.update(70)
    addonsettings.Specto_Settings()       	
    Progress.update(100)
	
    

if Config.getSetting("senyor") == 'true':

    if Config.getSetting("senyor") == 'true':
        if Config.getSetting("pvrset") == '0':
            Progress.create("מתקין לקוח  טלוויזיה חיה", "נא להמתין...")
            Progress.update(30)
        if Config.getSetting("pvrset") == '1':
            videoAddon.pvropenelec()
            Progress.create("מתקין לקוח  טלוויזיה חיה", "נא להמתין...")
            Progress.update(30)
        if Config.getSetting("pvrset") == '2':
            videoAddon.pvrolibraelec()
            Progress.create("מתקין לקוח  טלוויזיה חיה", "נא להמתין...")
            Progress.update(30)			
    else: pass

    
    Progress.create("מתקין מאגרי רפו...", "נא להמתין...")
    Progress.update(0)
    orphAddon.ToMeRepo()
    videoAddon.repositorymerlin()		    
    videoAddon.frenchdj()
    Progress.update(10)	
    orphAddon.TheWiz()
    videoAddon.thewizwall()	
    Progress.update(20)
    orphAddon.kodisrael()
    orphAddon.entertainmentrepo()
    Progress.update(30)
    orphAddon.featherence()
    Progress.update(40)
    orphAddon.abeksis()	
    Progress.update(50)
    orphAddon.xbmcisrael()
    orphAddon.repositoryGoodFellas()
    orphAddon.repositoryGoliath()
    orphAddon.repositorypodgod()
    orphAddon.repositoryshani()
    orphAddon.repositoryspoyser()	
    Progress.update(60)
    orphAddon.nirepo()	
    Progress.update(70)
    orphAddon.superrepo()
    Progress.update(80)
    orphAddon.xunitytalk()
    Progress.update(90)
    orphAddon.xbmchub()
    orphAddon.kodisenyor()
    orphAddon.senyortools()
    Progress.update(100)


    Progress.create("מתקין הרחבות...", "נא להמתין...")
    Progress.update(0)
    videoAddon.Exodus()
    videoAddon.Exodusrepo()			
    Progress.update(10)
    videoAddon.salts()
    videoAddon.tknorrisshared()	
    Progress.update(20)
    videoAddon.Phoenix() 
    videoAddon.ccloudtv() 	  
    Progress.update(30)
    videoAddon.specto()
    videoAddon.spectomedia()
    videoAddon.mrknowurlresolver()		
    videoAddon.filmkodi()		    
    videoAddon.goodfellas()	
    Progress.update(40)
    videoAddon.meta() 
    Progress.update(50)
    HeAddon.AnarchiTV()
    Progress.update(70)
    HeAddon.Vodil()
    videoAddon.gdrive()	
    Progress.update(75)
    HeAddon.reshet()
    HeAddon.makoTV()
    HeAddon.channelten()
    HeAddon.channelone()	
    videoAddon.xbmcisrael()
    videoAddon.iltwenty()
    Progress.update(80)
    videoAddon.skinxonfluence()
    Progress.update(85)
    videoAddon.contextthewizwall()
    videoAddon.DandyMedia()
    videoAddon.Evolve()	
    Progress.update(90)
    videoAddon.davidgdrive()		
    Progress.update(100)	

    Progress.create("מתקין הרחבות ישראליות...", "נא להמתין...")
    Progress.update(10)
    videoAddon.israeliveresolver()
    videoAddon.lastplayed()
    Progress.update(50)
    videoAddon.israelive()
    Progress.update(60)
    videoAddon.superaddon()	
    Progress.update(70)
    HeAddon.hotvod()
    Progress.update(80) 
    HeAddon.hetrailers()
    HeAddon.walla()
    Progress.update(90) 
    HeAddon.metasearch()	
    Progress.update(100)
	
    Progress.create("מתקין תלויות להרחבות...", "נא להמתין...")
    Progress.update(0)
    videoAddon.six()
    videoAddon.pyxbmct()
    Progress.update(20) 
    videoAddon.liveresolver()
    videoAddon.futures()  	
    videoAddon.f4mTester()
    videoAddon.commonmodule()
    videoAddon.scriptfavourites()
    Progress.update(40) 
    videoAddon.globalsearch()		
    videoAddon.TheYidcommon()		    
    videoAddon.singledispatch()
    videoAddon.youtube()
    videoAddon.metahandler()
    Progress.update(60) 
    videoAddon.librarydata()
    videoAddon.routing()
    videoAddon.autocompl()
    videoAddon.urlresolver()
    videoAddon.randomandlastitems()
    videoAddon.beautifulsoup4()		  		
    Progress.update(80) 
    videoAddon.html5lib()
    HeAddon.hebrew()
    videoAddon.autocompletion()		
    videoAddon.myconnpy()
    videoAddon.widgets()
    videoAddon.requests()	
    Progress.update(100)		
	
	
    Progress.create("מתקין הרחבות מוזיקה...", "נא להמתין...")
    Progress.update(0)
    MusicAddon.KMusicTube()
    videoAddon.t0mm0()
    videoAddon.requests()		
    Progress.update(10)
    MusicAddon.TheMusicSource()
    videoAddon.beautifulsoup()
    videoAddon.simpledownloader()		 
    videoAddon.parsedom()		
    videoAddon.commonplugincache()
    videoAddon.httplib2()
    videoAddon.youtubedl()
    videoAddon.signals()		
    videoAddon.urlresolver()
    videoAddon.simplejson()		
    Progress.update(20)
    MusicAddon.FeatherenceMusic()
    videoAddon.featherenceservice()		
    Progress.update(40)	
    MusicAddon.Jango()	
    Progress.update(60)
    MusicAddon.livehd()  
    videoAddon.frenchdj()		
    Progress.update(70)
    MusicAddon.ninfm()
    MusicAddon.ibavod()
    orphAddon.nirepo()	
    videoAddon.xbmcswift()
    videoAddon.html5lib()
    Progress.update(800)
    MusicAddon.merlinradio()	
    Progress.update(100)		

    Progress.create("מתקין הרחבות דוקומנטריה", "נא להמתין...")
    Progress.update(0)
    DocuAddon.Decado()	
    Progress.update(20)
    DocuAddon.Featherencedocu()
    Progress.update(40)
    DocuAddon.Documentarytube()
    Progress.update(60)	
    DocuAddon.Brettus()	
    Progress.update(80)
    DocuAddon.iconspire()		
    Progress.update(100)

    Progress.create("מתקין הרחבות לילדים", "נא להמתין...")
    Progress.update(0)
    HeAddon.KidsIl()
    videoAddon.xbmcisrael()	
    Progress.update(20)
    HeAddon.featherencekids()
    videoAddon.babytv()	
    Progress.update(50)
    HeAddon.kodisraelkids()	
    Progress.update(100)

    Progress.create("מתקין הרחבות כתוביות...", "נא להמתין...")
    Progress.update(0)
    DocuAddon.subcenter()
    Progress.update(20)
    DocuAddon.ktuvit()
    Progress.update(60)	
    DocuAddon.opensubtitles()		
    Progress.update(100)
	
    Progress.create("מתקין ערכת עיצוב...", "נא להמתין...")
    Progress.update(50)
    addonsettings.photos()
    Progress.update(100)	

    Progress.create("מתקין הגדרות מערכת", "נא להמתין...")
    Progress.update(20)
    addonsettings.PvrSettings()
    Progress.update(60)
    addonsettings.userdata()
    Progress.update(100)
	
    if Config.getSetting("lan") == 'true':
        if Config.getSetting("lanset") == '0':
            Progress.create("מתקין שפת מערכת...", "נא להמתין...")
            Progress.update(30)
        if Config.getSetting("lanset") == '1':
            addonsettings.englishlan()
            Progress.create("מתקין שפת מערכת...", "נא להמתין...")
            Progress.update(30)
        if Config.getSetting("lanset") == '2':
            addonsettings.rulan()
            Progress.create("מתקין שפת מערכת...", "נא להמתין...")
            Progress.update(30)			
    else: pass	
    videoAddon.lastset()	
    killxbmc()	 

else: pass



if Config.getSetting("Phenomenal") == 'true':

    if Config.getSetting("Phenomenal") == 'true':
        if Config.getSetting("pvrset") == '0':
            Progress.create("מתקין לקוח  טלוויזיה חיה", "נא להמתין...")
            Progress.update(30)
        if Config.getSetting("pvrset") == '1':
            videoAddon.pvropenelec()
            Progress.create("מתקין לקוח  טלוויזיה חיה", "נא להמתין...")
            Progress.update(30)
        if Config.getSetting("pvrset") == '2':
            videoAddon.pvrolibraelec()
            Progress.create("מתקין לקוח  טלוויזיה חיה", "נא להמתין...")
            Progress.update(30)			
    else: pass

    
    Progress.create("מתקין מאגרי רפו...", "נא להמתין...")
    Progress.update(0)
    orphAddon.ToMeRepo()
    videoAddon.repositorymerlin()		    
    Progress.update(10)	
    orphAddon.TheWiz()
    videoAddon.thewizwall()	
    Progress.update(20)
    orphAddon.kodisrael()
    Progress.update(30)
    orphAddon.featherence()
    Progress.update(40)
    orphAddon.xbmcisrael()
    Progress.update(50)
    orphAddon.kodisenyor()
    Progress.update(60)
    videoAddon.Exodusrepo()	
    Progress.update(75)
    videoAddon.filmkodi()
    Progress.update(80)
    orphAddon.merlin()
    Progress.update(85)
    videoAddon.goodfelles()
    Progress.update(90)
    videoAddon.ares()
    Progress.update(100)
 
    xbmc.executebuiltin("UpdateLocalAddons")
    xbmc.executebuiltin("UpdateAddonRepos")	 
 
    Progress.create("מתקין הרחבות...", "נא להמתין...")
    Progress.update(0)
    videoAddon.meta() 
    videoAddon.futures()
    videoAddon.requests()	
    Progress.update(50)
    HeAddon.metasearch()	
    videoAddon.gdrive()	
    Progress.update(75)
    videoAddon.contextthewizwall()
    videoAddon.davidgdrive()
    videoAddon.globalsearch()		
    Progress.update(100)	

    xbmc.executebuiltin("UpdateLocalAddons")
    xbmc.executebuiltin("UpdateAddonRepos")	 	
	
    Progress.create("מתקין תצורת תפריטים", "נא להמתין...")
    Progress.update(10)
    videoAddon.superaddon()	
    Progress.update(100)

    xbmc.executebuiltin("UpdateLocalAddons")
    xbmc.executebuiltin("UpdateAddonRepos")	 
	
    Progress.create("מתקין תלויות להרחבות...", "נא להמתין...")
    Progress.update(10)
    videoAddon.phenomenal()
    videoAddon.favourites()
    Progress.update(20) 
    videoAddon.autocompl()
    videoAddon.autocompletion()		
    videoAddon.arctic()
    videoAddon.modulet()  	
    videoAddon.studios()
    Progress.update(30) 
    videoAddon.librarydata()
    videoAddon.simplejson()	
    videoAddon.requests()	
    Progress.update(40) 
    videoAddon.beautifulsoup()
    videoAddon.commonplugincache()	
    videoAddon.artwork()
    videoAddon.resources()
    Progress.update(80) 
    videoAddon.unidecode()		
    videoAddon.helper()		    
    videoAddon.skinshortcuts()
    Progress.update(100)		

    xbmc.executebuiltin("UpdateLocalAddons")
    xbmc.executebuiltin("UpdateAddonRepos")	 
	
    Progress.create("מתקין הרחבות כתוביות...", "נא להמתין...")
    Progress.update(0)
    DocuAddon.subcenter()
    DocuAddon.torec()
    Progress.update(20)
    DocuAddon.ktuvit()
    Progress.update(60)	
    DocuAddon.opensubtitles()		
    Progress.update(100)

    xbmc.executebuiltin("UpdateLocalAddons")
    xbmc.executebuiltin("UpdateAddonRepos")	 
	
    Progress.create("מתקין ערכת עיצוב...", "נא להמתין...")
    Progress.update(50)
    addonsettings.pheomenalphotos()
    Progress.update(100)	

    xbmc.executebuiltin("UpdateLocalAddons")
    xbmc.executebuiltin("UpdateAddonRepos")	 	
	
    Progress.create("מתקין הגדרות מערכת", "נא להמתין...")
    Progress.update(20)
    addonsettings.PvrSettings()
    Progress.update(60)
    addonsettings.phenomenaluserdata()
    Progress.update(100)
    videoAddon.lastset()	
    xbmc.executebuiltin("UpdateLocalAddons")
    xbmc.executebuiltin("UpdateAddonRepos")	 
    xbmc.executebuiltin('RunScript(special://home/addons/plugin.program.sfbuild/resources/img/ltr.py)')	
    xbmc.executebuiltin('RunScript(special://home/addons/plugin.program.sfbuild/resources/img/fon.py)') 

else: pass



Config.setSetting(id='Phenomenal', value='false')
Config.setSetting(id='senyor', value='false')
Config.setSetting(id='deletekodi', value='false')
Config.setSetting(id='addonsset', value='false')



sys.exit()

