# session.py - A TCP connection session
#
# Copyright 2007 Nokia
# Author: Daniel d'Andrada T. de Carvalho <daniel.carvalho@indt.org.br>
#
# This file is part of mediahandler-skeleton.
#
# mediahandler-skeleton 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 3 of the
# License, or (at your option) any later version.
#
# mediahandler-skeleton 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with mediahandler-proxy. If not, see <http://www.gnu.org/licenses/>.

import SocketServer
import command as cmd
import socket
import shared

class Session(SocketServer.BaseRequestHandler):


    def setup(self):
        print self.client_address, 'connected!'

    def handle(self):
        while not shared.should_quit:
            data = self.request.recv(1024)

            if not data:
                # Connection was closed.
                break

            command = cmd.from_string(data, self.request)

            if command == None:
                continue

            if command.name == 'quit':
                self.request.send('<result>ok</result>')

                shared.should_quit = True

                # Make the server iterate over its while loop
                sock = socket.socket()
                sock.connect(('localhost', shared.server_port))
                sock.close()

            else:
                result = command.execute()
                self.request.send('<result>' + result + '</result>')

    def finish(self):
        print self.client_address, 'disconnected!'
