import logging; logger = logging.getLogger("morse." + __name__)

from morse.helpers.components import add_property
from morse.modifiers.abstract_modifier import AbstractModifier

class UTMModifier(AbstractModifier):
    """ 
    This modifier converts the coordinates generated by the MORSE simulator to use
    UTM global coordinates. This is achieved by setting the offset of the Blender
    origin with respect to the UTM reference. The offset can be either given in
    the modifier parameters, or globally defined as three
    properties of the ``Scene_Script_Holder`` object of the scene: ``UTMXOffset``,
    ``UTMYOffset`` and ``UTMZOffset``.
    
    .. note:: Due to limitation in Blender, to pass offset outside of range
      [-10000.0, 10000.0] as global scene properties,
      you need to pass the offset value as a string.

    This modifier attempts to alter data ``x``, ``y`` and ``z`` of modified components.

    The UTM modifier provides as modifiers:
    
    * :py:class:`morse.modifiers.utm.CoordinatesToUTM`
    * :py:class:`morse.modifiers.utm.CoordinatesFromUTM`

    """
    
    _name = "UTM"
    
    add_property('_x_offset', 0, "x_offset", type = "float", doc = "UTM X Offset")
    add_property('_y_offset', 0, "y_offset", type = "float", doc = "UTM Y Offset")
    add_property('_z_offset', 0, "z_offset", type = "float", doc = "UTM Z Offset")
        
    def initialize(self):
        """ Initialize the UTM coordinates reference. 
        """
        self._x_offset = float(self.parameter('x_offset', prop='UTMXOffset', default=0))
        self._y_offset = float(self.parameter('y_offset', prop='UTMYOffset', default=0))
        self._z_offset = float(self.parameter('z_offset', prop='UTMZOffset', default=0))
        logger.info("UTM reference point is (%s,%s,%s)" 
                    % (self._x_offset, self._y_offset, self._z_offset))

class CoordinatesToUTM(UTMModifier):
    """ Converts from Blender coordinates to UTM coordinates.
    """
    def modify(self):
        try:
            self.data['x'] += self._x_offset
            self.data['y'] += self._y_offset
            self.data['z'] += self._z_offset
        except KeyError as detail:
            self.key_error(detail)

class CoordinatesFromUTM(UTMModifier):
    """ Converts from UTM coordinates to Blender coordinates.
    """
    def modify(self):
        try:
            self.data['x'] -= self._x_offset
            self.data['y'] -= self._y_offset
            self.data['z'] -= self._z_offset
        except KeyError as detail:
            self.key_error(detail)
