import os, shutil, urllib, xbmcvfs, xbmcaddon, bottle, xbmcgui, tempfile
from bottle import route, request, static_file, run, template, sys
import xml.etree.ElementTree as ET

root_dir = xbmcvfs.translatePath("special://home/") + "addons/script.zhiboyuan.xiugai/"
edit_dir = root_dir + "code/edit/";
tempfile.tempdir = xbmcvfs.translatePath("special://temp/") 
bottle.TEMPLATE_PATH.append(os.path.join(root_dir, 'template'))

@route('/')
@route('/null')
@route('/edit/null')
def root(): 
	for curDir, dirs, files in os.walk(edit_dir):
		return template("index.tpl", files = files, dirs = dirs)

@route('/epg',method='POST')
def yingshe():
	y = xbmcaddon.Addon('pvr.iptvsimple')
	Epg = urllib.parse.unquote(request.forms["epg"])
	if Epg:
		try:
			y.setSettingInt(id="epgPathType", value=1)
			y.setSettingString(id="epgUrl", value=Epg)
		except:
			return "error"

@route('/yingshe',method='POST')
def yingshe():
	y = xbmcaddon.Addon('pvr.iptvsimple')
	Yfile = urllib.parse.unquote(request.forms["Yfile"])
	fileName = edit_dir + Yfile;
	if os.path.isfile(fileName):
		try:
			y.setSettingInt(id="m3uPathType", value=1)
			y.setSettingString(id="m3uUrl", value=fileName)
		except:
			return "error"
	elif os.path.isdir(fileName):
		try:
			y.setSettingInt(id="logoPathType", value=1)
			y.setSettingString(id="logoBaseUrl", value=fileName)
		except:
			return "error"

	
@route('/edit/<filename>')
def server_static(filename):
	fileName = edit_dir + filename;
	if os.path.isfile(fileName):		
		with open(fileName,"r",encoding="utf-8") as f:
			data = f.read()
		return template('text', text = data, filename = filename)

@route('/delete/<filename:path>',method='POST')
def delete(filename):
	fileName = edit_dir + filename;
	if os.path.isfile(fileName):
		os.remove(fileName)
	elif os.path.isdir(fileName):
		shutil.rmtree(fileName) 

@route('/static/<filename>')
def server_static(filename):
	return static_file(filename, root=edit_dir, mimetype = 'text/plain')

@route('/new/<filename>',method='POST')
def server_static(filename):	
	fileName = edit_dir + filename + ".m3u";
	if os.path.isfile(fileName):
		return "exists"
	else:
		os.mknod(fileName)
		with open(fileName,"r",encoding="utf-8") as f:
			data = f.read()
		return template('text', text = data, filename = filename)

@route('/code/<filename:path>')
def server_static(filename):
	code_path = root_dir + "/code/"
	return static_file(filename, root=code_path)

@route('/submit', method='POST')
def tijiao():
	str = request.json['data'];
	filename = edit_dir + request.json['name'];
	with open(filename,"w",encoding="utf-8") as f:
		data = f.write(str)

@route('/upload', method='POST')
def do_upload():
	fail_text=""
	fail_dir=""
	upFiles = request.files.getlist('m3uFile')
	Dir = request.files.getlist("uploadDir")
	if Dir:
		for x in Dir:
			child_dir = os.path.dirname(x.raw_filename)
			name, ext = os.path.splitext(x.raw_filename)
			if ext in ('.png', '.jpg', 'jepg'):	
				if not child_dir.count("/"):
					save_path = edit_dir + child_dir
					save_file = "{path}{file}".format(path=edit_dir,file=x.raw_filename)
					if not os.path.exists(save_path):
						os.makedirs(save_path)
					try:
						x.save(save_file)
					except OSError:
						fail_text += "{file}\\n".format(file=os.path.basename(x.raw_filename))
		return template("status.tpl", data = "上传成功",fail_text = fail_text );
	if upFiles:
		for upFile in upFiles:
			file_path = "{path}/{file}".format(path=edit_dir, file=upFile.raw_filename)
			try:
				upFile.save(file_path)
			except OSError:
				fail_text += "{file}\\n".format(file=os.path.basename(upFile.raw_filename))
		return template("status.tpl", data = "上传成功",fail_text = fail_text );

@route('/upload/<path>', method='POST')
def do_upload(path):
	fail_text = ""
	upload_img = request.files.get('upload_img')
	save_path = edit_dir + path
	if not os.path.exists(save_path):
		os.makedirs(save_path)
	file_path = "{path_save}/{file}".format(path_save=save_path, file=upload_img.raw_filename)
	if os.path.exists(file_path):
		return template("status-folder.tpl", data = "同名文件已存在，上传失败",path = path)
	upload_img.save(file_path)
	return template("status-folder.tpl", data = "上传成功",path = path)

@route('/<filename:path>')
def server_static(filename):
	fileName = edit_dir + filename;
	if os.path.isfile(fileName):
		return static_file(filename, root=edit_dir, mimetype = 'text/plain')
	if os.path.isdir(fileName):
		for curDir, dirs, files in os.walk(fileName):
			break
		files.sort()
		return template('folder',files = files, filename = filename)
if __name__ == '__main__':
	ADDONS = xbmcaddon.Addon()
	port = ADDONS.getSettingInt('port')
	try:
		run(host='0.0.0.0', port=port, quiet=True)
	except Exception as e:
		xbmcgui.Dialog().ok("修改直播源插件", str(e))
