#!/usr/bin/python

import os
import lib
import sys
import ConfigParser

config = ConfigParser.ConfigParser()
config.read("stream.conf")

media_plugin = config.get("Media", "engine")
exec("from plugins.media.%s import *" % media_plugin)

media = Media(config)

comm_plugin = config.get("Comm", "engine")
exec("from plugins.comm.%s import *" % comm_plugin)

# Start Our Server:
server = Server(config)

lib.log("Starting GMyth-Stream server")


'''
PROTOCOL DESCRIPTION
=====================

COMMAND OPTIONS

-> SETUP DESCRIPTION
|-> used to setup transcoding and streaming parameters
|-> must be used before any "PLAY" command
|-> e.g:

file://file_name mux vcodec vbitrate fps acodec abitrate width height options
dvd://title_number mux vcodec vbitrate fps acodec abitrate width height options

-> PLAY DESCRIPTION
 |-> used to start transcoding and streaming of file
 |-> must be used just if SETUP was used before
 |-> after it, _must_ send STOP

-> STOP DESCRIPTION
 |-> used to stop transcoding and streaming process
 |-> must be used just if PLAY was used before
 |-> must be used after PLAY

-> QUIT DESCRIPTION
 |-> used to quit the main loop (quit program)

'''
nextport = 0

while (server.finish == 0):
    conn, client, port = server.getRequest()
    server.sendMsg("Welcome to GMyth-Streamer Master")
    if nextport == 0:
        nextport = port

    while True:
        msg = server.getMsg(1024).strip()

        if not msg: break

        lib.log("Received %s from: %s" % (msg, client) )

        if msg == "SETUP":
            setup = server.getMsg(1024).strip().split(" ")
            size = len(setup)
            options = []

            if size < 10:
                server.sendMsg(lib.log("Wrong SETUP command from: %s" % client[0]))

            else:

                if size > 10:
                    i = 10
                    while (i < size):
                        options.append(setup[i])
                        i += 1

                nextport += 1
                ret = media.setup(setup[0], setup[1], setup[2], \
                                  setup[3], setup[4], setup[5],
                                  setup[6], setup[7], setup[8],
                                  nextport, options)

                if ret == 0:
                    server.Ack("SETUP")
                else:
                    server.sendMsg(lib.log(ret))


        elif msg == "PLAY":
            media.play()
            server.Ack("PLAY")
            server.sendMsg("STREAM PORT=%d" % nextport)

        elif msg == "STOP":
            media.stop()
            server.Ack("STOP")

        elif msg == "QUIT":
            server.finish = 1
            media.stop()
            server.Ack("QUIT")
            break

    lib.log("Closing connection with %s" % client[0])
    server.disconnect_client(conn)

server.stop()
del(server)
lib.log("Server stopped. Closing...")

