#  Copyright 2008-2009 Nokia Siemens Networks Oyj
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.


from java.lang import Byte, Short, Integer, Long, Boolean, Float, Double

from robot.errors import DataError


class ArgumentCoercer:

    def __init__(self, signatures):
        types = self._parse_types(signatures)
        self._coercers = [ _CoercionFunction(t, i+1) for i, t in types ]

    def _parse_types(self, signatures):
        types = {}
        for sig in signatures:
            for index, arg in enumerate(sig.args):
                types.setdefault(index, []).append(arg)
        types = types.items()
        types.sort()
        return types
        
    def __call__(self, args):
        return [ coercer(arg) for coercer, arg in zip(self._coercers, args) ]


class _CoercionFunction:

    _bool_types = [Boolean]
    _bool_primitives = ['boolean']
    _int_types = [Byte, Short, Integer, Long]
    _int_primitives = ['byte', 'short', 'int', 'long']
    _float_types = [Float, Double]
    _float_primitives = ['float', 'double']

    def __init__(self, arg_types, position):
        self._position = position
        self.__coercer = None
        for arg in arg_types:
            if not (self._set_bool(arg) or 
                    self._set_int(arg) or 
                    self._set_float(arg)):
                self.__coercer = self._no_coercion

    def __call__(self, arg):
        if not isinstance(arg, basestring):
            return arg
        return self.__coercer(arg)

    def _set_bool(self, arg):
        return self._set_coercer(arg, self._bool_types, 
                                 self._bool_primitives, self._to_bool)

    def _set_int(self, arg):
        return self._set_coercer(arg, self._int_types, 
                                 self._int_primitives, self._to_int)

    def _set_float(self, arg):
        return self._set_coercer(arg, self._float_types, 
                                 self._float_primitives, self._to_float)

    def _set_coercer(self, arg, type_list, primitive_list, coercer):
        if arg in type_list or str(arg) in primitive_list:
            if self.__coercer is None:
                self.__coercer = coercer
            elif self.__coercer != coercer:
                self.__coercer = self._no_coercion
            return True
        return False

    def _to_bool(self, arg):
        if arg.lower() == 'false':
            return False
        if arg.lower() == 'true':
            return True
        self._coercion_failed('boolean')

    def _to_int(self, arg):
        try:
            return long(arg)
        except ValueError:
            self._coercion_failed('integer')

    def _to_float(self, arg):
        try:
            return float(arg)
        except ValueError:
            self._coercion_failed('floating point number')

    def _no_coercion(self, arg):
        return arg

    def _coercion_failed(self, arg_type):
        raise DataError('Argument at position %d cannot be coerced to %s'
                        % (self._position, arg_type))


@@ -600,16 +600,28 @@
 ense.%0A%0A%0A
+import sys%0A%0A
 from jav
@@ -1172,24 +1172,16 @@
 n types%0A
-        
 %0A    def
@@ -1341,43 +1341,8 @@
 an%5D%0A
-    _bool_primitives = %5B'boolean'%5D%0A
     
@@ -1383,16 +1383,86 @@
 , Long%5D%0A
+    _float_types = %5BFloat, Double%5D%0A    _bool_primitives = %5B'boolean'%5D%0A
     _int
@@ -1523,75 +1523,321 @@
 oat_
-typ
+primitiv
 es = %5B
-F
+'f
 loat
+'
 , 
-D
+'d
 ouble
+'
 %5D%0A    
-_float_primitives = %5B'float', 'double'%5D
+if sys.version_info%5B:2%5D %3E (2,2):%0A        pattern = %22%3Ctype '%25s'%3E%22%0A        _bool_primitives =  %5B pattern %25 'boolean' %5D%0A        _int_primitives =   %5B pattern %25 p for p in _int_primitives %5D%0A        _float_primitives = %5B pattern %25 p for p in _float_primitives %5D%0A        del pattern
 %0A%0A  
@@ -2007,33 +2007,32 @@
 set_bool(arg) or
- 
 %0A               
@@ -2057,17 +2057,16 @@
 (arg) or
- 
 %0A       
@@ -2366,25 +2366,24 @@
 _bool_types,
- 
 %0A           
@@ -2518,33 +2518,32 @@
 self._int_types,
- 
 %0A               
@@ -2684,17 +2684,16 @@
 t_types,
- 
 %0A       

Fix java argument coercion with Jython 2.5, issue 469