import sys, os, os.path
from kodiswift import xbmc, xbmcgui, CLI_MODE
from kodiswift import Plugin, storage
from resources.lib.content import util


#plugin = Plugin()
#plugin.load_addon_settings()
#playlist = plugin.get_setting("general_playlist",str)
#proxy_url = plugin.get_setting("general_proxy_url",str)

cmd = sys.argv[1]
#title = sys.argv[2]
#data = sys.argv[3]
#img = sys.argv[4]
#desc = sys.argv[5]

if cmd in ("add", "delete"):
    from resources.lib.content.sources.config import Source
    cfg = Source()
    lists = cfg.get_lists()
    titles = [cfg.get_title(name) for name in lists]


if cmd == "add":
    if not CLI_MODE:
        ret = xbmcgui.Dialog().select("Select menu",titles)
    else:
        ret = 3
    cfg.add_item(lists[ret],sys.argv[2:])
    cfg.write_streams()

elif cmd == "delete":
    xbmcgui.Dialog().ok("Info","Not yet implemented!")

elif cmd == "playlist":
    title = sys.argv[2]
    data = sys.argv[3]
    playlist = sys.argv[4]
    proxy_url = sys.argv[5]
    if not os.path.exists(playlist):
        pl = open(playlist,"wb")
        pl.write('#EXTM3U\n')
    else:
        pl = open(playlist,"a")
    urlp = util.streamproxy_encode2(data,{},proxy_url)
    if isinstance(urlp,unicode):
        urlp = urlp.encode("utf8")
    if isinstance(title,unicode):
        title = title.encode("utf8")
    pl.write("#EXTINF:0,%s\n%s\n"%(title,urlp))
    pl.close()
    #plugin.notify("Item '%s' added to %s"%(title,playlist), "Info", 10000, xbmcgui.NOTIFICATION_INFO)

elif cmd == "download":
    xbmcgui.Dialog().ok("Info","Not yet implemented!")

else:
    xbmcgui.Dialog().ok("Error","Wrong command")



#mode = "a" if os.path.exists("context_menu.log") else "w"
#with open("context_menu.log", mode) as f:
#    f.write("%s %s %s %s", sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4])
