#!/usr/bin/python3

import tornado.ioloop, tornado.web, os
import mplayer_ctl


class Index(tornado.web.RequestHandler):
    def get(self):
        self.redirect("/web/index.html", permanent=True)
 
class PlayerControl(tornado.web.RequestHandler):
    
    def get(self):
        cmd = None
        c   = self.get_argument('cmd')
        
        if c == "new_artist_stream":
            cmd = mplayer_ctl.Cmd(mplayer_ctl.CMD_NEW_ARTIST_STREAM, {
                "name" : self.get_argument('name')
            })
        
        elif c == "stop_stream":
            cmd = mplayer_ctl.Cmd(mplayer_ctl.CMD_STOP_STREAM)

        if cmd is not None:
            print("Adding command:", cmd)
            mplayer_ctl.cmd_queue.insert(0, cmd)

        self.redirect("/")

urls = [
    (r"/", Index),
    (r"/player_control", PlayerControl),
]

settings = {
    "static_path"       : os.path.join(os.path.dirname(__file__),  "web"),
    "static_url_prefix" : "/web/",
    "debug"             : True,
}

app = tornado.web.Application(urls, **settings)

if __name__ == "__main__":
    print("Yams PI client")

    # Kick off mplayer control thread

    mplayer_ctl.start({
        "streaming_url" : "http://yozh.devt.de:9092",
        "default_url"   : "http://web:gemasuxx@devt.de:5051/pleasuredome",
    })

    # Kick off tornado

    app.listen(80)
    tornado.ioloop.IOLoop.instance().start()
