#!/bin/env python
# -*- coding: utf-8 -*-
"""
PlayStreamProxy server
Provides API to ContetSources + stream serving to play via m3u8 playlists
"""

import os, sys, time
import urllib,urlparse
from urllib import unquote, quote
#import cookielib,urllib2
import requests
import re, json
from diskcache import Cache

import bottle
from bottle import Bottle, hook, response, route, request, run

#if not sys.platform == 'win32':
import daemonize

from ContentSources import ContentSources
from sources.SourceBase import stream_type
import util
from util import streamproxy_decode3, streamproxy_encode3

try:
    from requests.packages.urllib3.exceptions import InsecureRequestWarning
    requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
except:
    pass

# Default arguments
SERVER = "wsgiref"
PORT_NUMBER = 8880
DEBUG = False

cunicode = lambda s: s.decode("utf8") if isinstance(s, str) else s
cstr = lambda s: s.encode("utf8") if isinstance(s, unicode) else s
headers2dict = lambda  h: dict([l.strip().split(": ") for l in h.strip().splitlines()])

headers0 = headers2dict("""
User-Agent: GStreamer souphttpsrc libsoup/2.52.2
icy-metadata: 1
""")
headers0_ = headers2dict("""
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36
""")

cur_directory = os.path.dirname(os.path.realpath(__file__))
slinks = {}
sessions = {}

cfg_file = "streams.cfg"
sources0 = ContentSources("", cfg_file)

cache_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "cache")
s0 = Cache(cache_dir)
s0["n"] = 0
s0["sources"] = sources0

app = Bottle()

@app.hook('before_request')
def set_globals():
    global s, sources, cmd, data, headers, qs
    cmd, data, headers, qs = streamproxy_decode3(request.url)
    cache_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "cache")
    s = Cache(cache_dir)
    sources = s["sources"]

# http://localhost:8880/playstream/ltc%3A%3Acontent%2Flive-streams%2F101%3Finclude%3Dquality/
#@app.route('/')
@app.route('/playstream/<url:re:.*>')
def fetch_source(url):
    global s, sources, cmd, data, headers, qs
    return 'cmd=%s, data=%s, qs=%s'% (cmd, data, str(qs))



####################################################################
# Run WSGI server
def start(server,port):
    options = {}
    if server == "mtwsgi":
        import mtwsgi
        server = mtwsgi.MTServer
        options = {"thread_count": 3,}

    run(app=app,server=server, host='0.0.0.0',
            port=port,
            #reloader=True,
            quiet=False,
            plugins=None,
            debug=True,
            #thread_count=3,
            config=None,
            **options)

def print_headers(headers):
    for h in headers:
        print "%s: %s"%(h,headers[h])

def del_headers(headers0,tags):
    headers = headers0.copy()
    for t in tags:
        if t in headers:
            del headers[t]
        if t.lower() in headers:
            del headers[t.lower()]
    return headers

def hls_base(url):
    base = url.split("?")[0]
    base = "/".join(base.split("/")[0:3])+ "/"
    rest = url.replace(base, "")
    return base

def hls_base2(url):
    base = url.split("?")[0]
    base = "/".join(base.split("/")[0:-1])+ "/"
    rest = url.replace(base, "")
    return base


if __name__ == '__main__':
    if len(sys.argv) > 1:
        pid = "/var/run/playstreamproxy2.pid"
        daemon = daemonize.Daemon(start, pid)
        server = sys.argv[2] if len(sys.argv) > 2 else SERVER
        port = sys.argv[3] if len(sys.argv) > 3 else PORT_NUMBER
        if "start" == sys.argv[1]:
            daemon.start(server,port)
            daemon.is_running()
        elif "stop" == sys.argv[1]:
            daemon.stop()
        elif "restart" == sys.argv[1]:
            daemon.restart()
            daemon.is_running()
        elif "manualstart" == sys.argv[1]:
            start(server,port)
        elif "status" == sys.argv[1]:
            daemon.is_running()
        else:
            print "Unknown command"
            print "usage: %s start|stop|restart|manualstart" % sys.argv[0]
            sys.exit(2)
        sys.exit(0)
    else:
        print "usage: %s start|stop|restart|manualstart" % sys.argv[0]
        sys.exit(2)
