# util.py - Utility functions
#
# 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 re

def find_command_name(string):
    '''
    Returns the command name in the given string of None
    if the strings doesn't have a well formed command
    '''
    if not string.startswith('<'):
        return None

    if not string.endswith('>'):
        return None

    index = string.find('>')
    if index == len(string) - 1 or index == -1:
        return None

    opening_tag_name = string[1:index]

    index = string.rfind('</',index+1)
    if index == -1:
        return None

    closing_tag_name = string[index+2:len(string)-1]

    if opening_tag_name != closing_tag_name:
        return None

    return opening_tag_name


def parse_command(string):
    '''
    string = "<foo>bar</foo>" -> {'name' : 'foo', 'params' = 'bar' }

    Returns a dictionary on success and None if element doesn't contain a well
    formed command.
    '''
    cmd_name = find_command_name(string)

    if cmd_name == None:
        return None

    match = re.compile('(?<=\<' + cmd_name + '\>)(.*)(?=\</' + cmd_name + '\>)').search(string)
    if match == None:
        return None

    params = match.group()

    return {'name' : cmd_name, 'params' : params}

