#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#  Copyright (C) 2010 by Atzm WATANABE <atzm@atzm.org>
#
#  This program is free software; you can redistribute it and/or modify it
#  under the terms of the GNU General Public License (version 2) as
#  published by the Free Software Foundation.  It 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.
#
# $Id$
#

import base64
import ConfigParser
import SimpleXMLRPCServer

try:
    import cStringIO as _StringIO
except ImportError:
    import StringIO as _StringIO

from pycodebattler import warrior


CONFIG = ConfigParser.SafeConfigParser()
CONFIG.read('pycgibattler.conf')


class ScouterError(RuntimeError):
    pass


def scout(data):
    if 'version' not in data:
        raise ScouterError('version not found')
    if data['version'] != 1.0:
        raise ScouterError('invalid version')
    if 'code' not in data:
        raise ScouterError('code not found')
    if not isinstance(data['code'], basestring):
        raise ScouterError('invalid code (not string)')

    try:
        code = base64.standard_b64decode(data['code'])
    except TypeError:
        raise ScouterError('invalid code (not base64 encoded)')

    if len(code) > CONFIG.getint('limit', 'max_size'):
        raise ScouterError('code length exceeded')

    wrr = warrior.Warrior.make('', _StringIO.StringIO(code))

    return {
        'version': 1.0,
        'result':  {
            'hitpoint':      wrr.hitpoint(),
            'skillpoint':    wrr.skillpoint(),
            'strength':      wrr.strength(),
            'concentration': wrr.concentration(),
            'defense':       wrr.defense(),
            'agility':       wrr.agility(),
            'luck':          wrr.luck(),
        },
    }


if __name__ == '__main__':
    handler = SimpleXMLRPCServer.CGIXMLRPCRequestHandler()
    handler.register_function(scout, 'Scout')
    handler.handle_request()
