# -*- coding: utf-8 -*-
import xbmcgui, xbmc, xbmcaddon, xbmcvfs, codecs
import time, sys, os, gzip, io, requests, os,os.path, stat, subprocess
PY2 = sys.version_info[0] == 2
PY3 = sys.version_info[0] == 3
if PY2:
	from urllib import urlretrieve
	from urllib2 import build_opener
else:
	from urllib.request import build_opener, urlretrieve
transPath = xbmc.translatePath if PY2 else xbmcvfs.translatePath
temp = transPath("special://profile/addon_data/plugin.video.tools/temp/")
epg = transPath('special://profile/addon_data/plugin.video.tools/epg.xml')
epgdb = transPath('special://profile/Database/Epg13.db')
#url1 = ADDON.getSetting('epg1')
#url2 = ADDON.getSetting('epg2')
#url3 = ADDON.getSetting('epg3')
#url4 = ADDON.getSetting('epg4')
#url5 = ADDON.getSetting('epg5')
#url6 = ADDON.getSetting('epg6')
#url7 = ADDON.getSetting('epg7')
#url8 = ADDON.getSetting('epg8')

	
def delete(path):
    dirs, files = xbmcvfs.listdir(path)
    for file in files:
        xbmcvfs.delete(path+file)
    for dir in dirs:
        delete(path + dir + '/')
    xbmcvfs.rmdir(path)

def windows():
    if os.name == 'nt':
        return True
    else:
        return False

def busybox_location():
    if xbmc.getCondVisibility('system.platform.android'):
        busybox_src = transPath("special://home/addons/plugin.video.tools/resources/busybox")
        busybox_dst = transPath("special://xbmc/busybox")
        if not xbmcvfs.exists(busybox_dst) and busybox_src != busybox_dst:
            xbmcvfs.copy(busybox_src, busybox_dst)
        busybox = busybox_dst
    elif xbmc.getCondVisibility('system.platform.linux'):
        busybox = transPath("special://home/addons/plugin.video.tools/resources/busybox")
    else:
        busybox = transPath("special://home/addons/plugin.video.tools/resources/busybox.exe")
    if busybox:
        try:
            st = os.stat(busybox)
            if not (st.st_mode & stat.S_IXUSR):
                try:
                    os.chmod(busybox, st.st_mode | stat.S_IXUSR)
                except:
                    pass
        except:
            pass
    if xbmcvfs.exists(busybox):
        return busybox
    else:
        xbmcgui.Dialog().notification("Tools","busybox not found",xbmcgui.NOTIFICATION_ERROR)
		
def py3_dec(d, encoding='utf-8'):
	if PY3 and isinstance(d, bytes):
		d = d.decode(encoding)
	return d
	
def get(url, agent='Mozilla/5.0 (Windows NT 10.0; WOW64; rv:60.0) Gecko/20100101 Firefox/60.0'):
	if '.xz' in url :
		xbmcvfs.mkdirs("special://profile/addon_data/plugin.video.tools/temp/")
		content = spezial(url)
	else:
		opener = build_opener()
		opener.addheaders = [('User-Agent', agent)]
		response = opener.open(url, timeout=100)
		if response.info().get('Content-Type') == 'application/x-gzip' or '.gz' in url:
			content = py3_dec(gzip.GzipFile(fileobj=io.BytesIO(response.read())).read())
		else:
			content = py3_dec(response.read())
	return content

def spezial(urls):
    xml_urls = [urls]
    for url in xml_urls:
        filename = transPath("special://profile/addon_data/plugin.video.tools/temp/" + url.rsplit('?',1)[0].rsplit('/',1)[-1])
        try:
            with open(filename,'wb') as f:
                if url.startswith('http') or url.startswith('ftp'):
                    data = requests.get(url).content
                    f.write(data)
                else:
                    f.write(xbmcvfs.File(url).read())
        except:
            continue
        if filename.endswith('.xz'):
            f = open(filename+".xml","w")
            subprocess.call([busybox_location(),"xz","-dc",filename],stdout=f,shell=windows())
            f.close()
            data = xbmcvfs.File(filename+'.xml','r').read()
        else:
            if filename.startswith("http"):
                data = requests.get(filename).content
            else:
                f = open(filename,'r')
                data = f.read()
                f.close()
    return data

def newepg():
	xbmcvfs.mkdirs("special://profile/addon_data/plugin.video.tools/")
	newxml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<tv generator-info-name=\"Michaz\">\n"
	end = '</tv>'
	#urls = [i for i in [url1, url2, url3, url4, url5, url6, url7, url8] if i !=""]
	urls = ["http://ricxepg.nl/epg_data/rytecDE_Basic.gz", "http://ricxepg.nl/epg_data/rytecAT_Basic.gz", "http://ricxepg.nl/epg_data/rytecDE_Common.gz", "http://ricxepg.nl/epg_data/rytecDE_SportMovies.gz", "http://195.154.221.171/epg/guidegermany.xml"]
	#urls = ["http://ricxepg.nl/epg_data/rytecDE_Basic.gz", "http://ricxepg.nl/epg_data/rytecAT_Basic.gz", "http://ricxepg.nl/epg_data/rytecDE_Common.gz", "http://ricxepg.nl/epg_data/rytecDE_SportMovies.gz"]
	urlretrieve('https://www.dropbox.com/s/xdsvml1znb2h6ak/aktuell.m3u?dl=1', transPath('special://profile/addon_data/plugin.video.tools/channels.m3u'))
	#path = ADDON.getSetting('m3uPath')
	#if ADDON.getSetting('choose_source') == '0' and ADDON.getSetting('m3uUrl') !='':
		#urlretrieve(ADDON.getSetting('m3uUrl'), transPath('special://profile/addon_data/plugin.video.tools/channels.m3u'))
	fehler = ''
	try:
		#while fehler == "":
		for url in urls:
			string = get(url)
			oben = string.find('<channel')
			unten = string.index('</tv>')
			newxml += string[oben:unten]
	except:
		fehler = url
	if fehler != "":
		xbmcgui.Dialog().notification('TOOLS', 'Fehler bei '+url, xbmcgui.NOTIFICATION_ERROR, 5000)
		xbmcaddon.Addon().setSetting('aktuell', "Fehler bei "+url)
	else:
		xbmcaddon.Addon().setSetting('aktuell', 'aktualisiert am '+time.strftime('%d.%b %H:%M'))
		xbmc.executeJSONRPC('{"jsonrpc":"2.0","id":1,"method":"Addons.SetAddonEnabled","params":{"addonid":"pvr.iptvsimple","enabled":false}}')
		time.sleep(1)
		with codecs.open(epg, 'w', encoding='utf8') as g:
			g.write((newxml+end))
		time.sleep(1)
		xbmc.executeJSONRPC('{"jsonrpc":"2.0","id":1,"method":"Addons.SetAddonEnabled","params":{"addonid":"pvr.iptvsimple","enabled":true}}')
		xbmcgui.Dialog().notification('TOOLS', 'EPG Aktualisierung fertig', xbmcgui.NOTIFICATION_INFO, 2000)
	delete(temp)
	return True