 '''
 # GMyth-Stream
 #
 # @file plugins/comm/xmlrpc.py
 #
 # @brief <p> Plugin for GMyth-Stream
 #
 # Copyright (C) 2007 INdT - Instituto Nokia de Tecnologia.
 # @author Artur Duque de Souza <artur.souza@indt.org.br>
 #
 #
 # This program is free software; you can redistribute it and/or modify
 # it under the terms of the GNU Lesser General Public License as published by
 # the Free Software Foundation; either version 2 of the License, or
 # (at your option) any later version.
 #
 # This program is distributed in the hope that it will be useful,
 # but WITHOUT ANY WARRANTY; without even the implied warranty of
 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 # GNU General Public License for more details.
 #
 # You should have received a copy of the GNU Lesser General Public License
 # along with this program; if not, write to the Free Software
 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 #
 '''

import SimpleXMLRPCServer


class Handler:

    def __init__(self, pool):
        self.pool = pool

    def _listMethods(self):
        return ['Setup', 'Play', 'Stop', 'Close']

    def _methodHelp(self, method):

        if method == 'Setup':
            return "Setup the Media: Setup(filename,codec,bitrate,widht,height,port)"
        elif method == 'Play':
            return "Play the Media: Play()"
        elif method == 'Stop':
            return "Stop the Media: Stop()"
        elif method == 'Close':
            return "Close the connection: Close()"
        else:
            # By convention, return empty
            # string if no help is available
            return ""


    def Setup(self, filename, codec, bitrate, width, height, port):
        self.pool.append("SETUP")
        self.pool.append("%s %s %s %s %s %s" % (filename, codec, bitrate,\
                                             width, height, port))
        return 0

    def Play(self):
        self.pool.append("PLAY")
        return 0

    def Stop(self):
        self.pool.append("STOP")
        return 0

    def Close(self):
        self.pool.append("CLOSE")
        return 0


class Server:

    def __init__(self, config):
        self.host = 'localhost'
        self.port = int(config.get("Comm", "port"))
        self.finish = 0
        self.pool = []

        self.handler = Handler(self.pool)

        self.xmlrpc = SimpleXMLRPCServer.SimpleXMLRPCServer((self.host, self.port))
        self.xmlrpc.register_instance(self.handler)


    def getMsg(self, size):
        try:
            return self.pool.pop(0)
        except IndexError:
            return ""

    def getRequest(self):
        self.xmlrpc.handle_request()
        return (0, "RPC Client")

    def disconnect_client(self, connection):
        connection = 0

    def stop(self):
        self.xmlrpc.server_close()
