# Copyright (C) 2011 Canonical Ltd
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of version 3 of the GNU General Public License as
# published by the Free Software Foundation.
#
# This program 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.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA



"""Python bindings for the GEIS v2 gesture recognition interface.

Do not use this module directly -- the public API is provided by the 'geis'
module.
"""

import ctypes
import ctypes.util
import _geis_bindings
import re
import sys


class GeisError(Exception):
    """ A general error has occurred internally in GEIS.
    """
    def __init__(self, reason):
        Exception.__init__(self, reason)


class NoMoreEvents(Exception):
    """ Raised by the event dispatch mechanism to indicate there are no
        pending events in the queue.
    """

    def __init__(self):
        Exception.__init__(self, 'geis event queue is empty')



def _check_null(ret, func, args):
    """ Converts a NULL pointer return value into an Exception.
    """
    if ret == 0:
        raise GeisError("%s failed" % func.__name__)
    return ret

_EventCallback = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.c_void_p,
                                  ctypes.py_object)

_geis_lib = ctypes.CDLL(ctypes.util.find_library("geis"))
try:
    _geis_new = _geis_lib.geis_new
    _geis_new.restype = ctypes.c_void_p
    _geis_new.errcheck = _check_null
    _geis_delete = _geis_lib.geis_delete
    _geis_get_configuration = _geis_lib.geis_get_configuration
    _geis_dispatch_events = _geis_lib.geis_dispatch_events
    _geis_register_class_callback = _geis_lib.geis_register_class_callback
    _geis_register_device_callback = _geis_lib.geis_register_device_callback
    _geis_register_event_callback = _geis_lib.geis_register_event_callback
    _geis_next_event = _geis_lib.geis_next_event

    _geis_subscription_new = _geis_lib.geis_subscription_new
    _geis_subscription_new.restype = ctypes.c_void_p
    _geis_subscription_new.errcheck = _check_null
    _geis_subscription_delete = _geis_lib.geis_subscription_delete
    _geis_subscription_activate = _geis_lib.geis_subscription_activate
    _geis_subscription_deactivate = _geis_lib.geis_subscription_deactivate
    _geis_subscription_name = _geis_lib.geis_subscription_name

    _geis_attr_name = _geis_lib.geis_attr_name
    _geis_attr_name.restype = ctypes.c_char_p
    _geis_attr_type = _geis_lib.geis_attr_type
    _geis_attr_value_to_pointer = _geis_lib.geis_attr_value_to_pointer

    _geis_event_type = _geis_lib.geis_event_type
    _geis_event_attr_count = _geis_lib.geis_event_attr_count
    _geis_event_attr = _geis_lib.geis_event_attr
    _geis_event_attr.restype = ctypes.c_void_p

    _geis_gesture_class_unref = _geis_lib.geis_gesture_class_unref
    _geis_gesture_class_name = _geis_lib.geis_gesture_class_name
    _geis_gesture_class_name.restype = ctypes.c_char_p
    _geis_gesture_class_id = _geis_lib.geis_gesture_class_id
    _geis_gesture_class_attr_count = _geis_lib.geis_gesture_class_attr_count
    _geis_gesture_class_attr = _geis_lib.geis_gesture_class_attr
    _geis_gesture_class_attr.restype = ctypes.c_void_p

    _geis_device_ref = _geis_lib.geis_device_ref
    _geis_device_unref = _geis_lib.geis_device_unref
    _geis_device_name = _geis_lib.geis_device_name
    _geis_device_name.restype = ctypes.c_char_p
    _geis_device_id = _geis_lib.geis_device_id
    _geis_device_attr_count = _geis_lib.geis_device_attr_count
    _geis_device_attr = _geis_lib.geis_device_attr
    _geis_device_attr.restype = ctypes.c_void_p

    _geis_touchset_touch_count = _geis_lib.geis_touchset_touch_count
    _geis_touchset_touch = _geis_lib.geis_touchset_touch
    _geis_touchset_touch.restype = ctypes.c_void_p

    _geis_touch_attr_count = _geis_lib.geis_touch_attr_count
    _geis_touch_attr = _geis_lib.geis_touch_attr
    _geis_touch_attr.restype = ctypes.c_void_p

    _geis_groupset_group_count = _geis_lib.geis_groupset_group_count
    _geis_groupset_group = _geis_lib.geis_groupset_group
    _geis_groupset_group.restype = ctypes.c_void_p

    _geis_group_frame_count = _geis_lib.geis_group_frame_count
    _geis_group_frame = _geis_lib.geis_group_frame
    _geis_group_frame.restype = ctypes.c_void_p

    _geis_frame_attr_count = _geis_lib.geis_frame_attr_count
    _geis_frame_attr = _geis_lib.geis_frame_attr
    _geis_frame_attr.restype = ctypes.c_void_p
    _geis_frame_is_class = _geis_lib.geis_frame_is_class
    _geis_frame_touchid_count = _geis_lib.geis_frame_touchid_count
    _geis_frame_touchid = _geis_lib.geis_frame_touchid

except AttributeError as ex:
    print(ex)
    sys.exit(1)


class GestureClass(object):
    """Describes a class of gestures.
    """

    def __init__(self, attr):
        self._class = _geis_attr_value_to_pointer(attr)
        self._id = _geis_gesture_class_id(self._class)
        self._name = _geis_gesture_class_name(self._class).decode('utf-8')
        self._attr_count = _geis_gesture_class_attr_count(self._class)
        self._attrs = {}
        for i in range(self._attr_count):
            attr = _geis_gesture_class_attr(self._class, i)
            attr_name = _geis_attr_name(attr).decode('utf-8')
            self._attrs[attr_name] = _attr_types.get(_geis_attr_type(attr),
                                       _attr_type_unknown)(attr)

    @property
    def _as_parameter_(self):
        return self._class

    def id(self):
        """ Gets the gesture class's system identifier (an integer).
        """
        return self._id

    def name(self):
        """ Gets the gesture class's self-identified name.
        """
        return self._name

    def attrs(self):
        """ Gets the named attributes associated with the gesture class.
        """
        return self._attrs


class Device(object):
    """Describes a touchable device.
    """

    def __init__(self, attr):
        self._device = _geis_attr_value_to_pointer(attr)
        self._id = _geis_device_id(self._device)
        self._name = _geis_device_name(self._device).decode('utf-8')
        self._min_x = 0.0
        self._min_y = 0.0
        self._max_x = 0.0
        self._max_y = 0.0
        self._attr_count = _geis_device_attr_count(self._device)
        self._attrs = {}
        for i in range(self._attr_count):
            attr = _geis_device_attr(self._device, i)
            attr_name = _geis_attr_name(attr).decode('utf-8')
            self._attrs[attr_name] = _attr_types.get(_geis_attr_type(attr),
                                       _attr_type_unknown)(attr)
            if re.search("Abs MT Position X \d+ min", attr_name):
                self._min_x = self._attrs[attr_name]
            if re.search("Abs MT Position X \d+ max", attr_name):
                self._max_x = self._attrs[attr_name]
            if re.search("Abs MT Position Y \d+ min", attr_name):
                self._min_y = self._attrs[attr_name]
            if re.search("Abs MT Position Y \d+ max", attr_name):
                self._max_y = self._attrs[attr_name]

    def id(self):
        """ Gets the device's system identifier (an integer).
        """
        return self._id

    def name(self):
        """ Gets the device's self-identified name.
        """
        return self._name

    def extents(self):
        """ Gets the device's defined extents (bounding box).

            Returns: A tuple of (min X, min Y, max X, max Y).
        """
        return (self._min_x, self._min_y, self._max_x, self._max_y)

    def attrs(self):
        """ Gets the named attributes associated with the device.
        """
        return self._attrs


class Touch(object):
    """Represents a particular touch."""

    def __init__(self, touch):
        self._touch = touch
        self._attr_count = _geis_touch_attr_count(self._touch)

    def id(self):
        """ Gets the persistent identifier of the touch.
        """
        return _geis_lib.geis_touch_id(self._touch)

    def attrs(self):
        """ Gets the attributes of the touch.
        """
        attr_list = {}
        for i in range(self._attr_count):
            attr = _geis_touch_attr(self._touch, i)
            attr_name = _geis_attr_name(attr).decode('utf-8')
            attr_list[attr_name] = _attr_types.get(_geis_attr_type(attr),
                                       _attr_type_unknown)(attr)
        return attr_list


class Touchset(object):
    """A collection of Touch objects."""

    def __init__(self, attr):
        self._touchset = _geis_attr_value_to_pointer(attr)
        self._count = _geis_touchset_touch_count(self._touchset)
        self._index = 0

    def __len__(self):
        return self._count

    def __iter__(self):
        return self

    def __next__(self):
        """ Gets the next touch in the touchset as an iterable.
        """
        if self._index == self._count:
            raise StopIteration
        touch = Touch(_geis_touchset_touch(self._touchset, self._index))
        self._index = self._index + 1
        return touch


class Groupset(object):
    """A collection of Group objects."""

    def __init__(self, attr):
        self._groupset = _geis_attr_value_to_pointer(attr)
        self._count = _geis_groupset_group_count(self._groupset)
        self._index = 0

    def __len__(self):
        return self._count

    def __iter__(self):
        return self

    def __next__(self):
        """ Gets the next group in the groupset as an iterable.
        """
        if self._index == self._count:
            raise StopIteration
        touch = Group(_geis_groupset_group(self._groupset, self._index))
        self._index = self._index + 1
        return touch


class Group(object):
    """A set of Frame objects made up of a combination of touches."""

    def __init__(self, group):
        self._group = group
        self._count = _geis_group_frame_count(self._group)
        self._index = 0

    def __len__(self):
        return self._count

    def __iter__(self):
        return self

    def id(self):
        return _geis_lib.geis_group_id(self._group)

    def __next__(self):
        """ Gets the next frame in the group as an iterable.
        """
        if self._index == self._count:
            raise StopIteration
        frame = Frame(_geis_group_frame(self._group, self._index))
        self._index = self._index + 1
        return frame


class Frame(object):
    """A gesture frame."""

    def __init__(self, frame):
        self._frame = frame

    def id(self):
        return _geis_lib.geis_frame_id(self._frame)

    def attrs(self):
        attr_list = {}
        for i in range(_geis_frame_attr_count(self._frame)):
            attr = _geis_frame_attr(self._frame, i)
            attr_name = _geis_attr_name(attr).decode('utf-8')
            attr_list[attr_name] = _attr_types.get(_geis_attr_type(attr),
                                          _attr_type_unknown)(attr)
        return attr_list

    def is_class(self, gclass):
        return _geis_frame_is_class(self._frame, gclass)

    def touches(self):
        touch_list = []
        for i in range(_geis_frame_touchid_count(self._frame)):
            touch_list.append(_geis_frame_touchid(self._frame, i))
        return touch_list


def _pointer_type_class(attr):
    """ Converts a generic attr into a GestureClass object.
    """
    return GestureClass(attr)


def _pointer_type_device(attr):
    """ Converts a generic attr into a Device object.
    """
    return Device(attr)


def _pointer_type_groupset(attr):
    """ Converts a generic attr into a Groupset object.
    """
    return Groupset(attr)


def _pointer_type_touchset(attr):
    """ Converts a generic attr into a Touchset object.
    """
    return Touchset(attr)


def _pointer_type_unknown(attr):
    print("unknown pointer type ")
    return None


_attr_pointer_type = { 
    _geis_bindings.GEIS_EVENT_ATTRIBUTE_CLASS:    _pointer_type_class,
    _geis_bindings.GEIS_EVENT_ATTRIBUTE_DEVICE:   _pointer_type_device,
    _geis_bindings.GEIS_EVENT_ATTRIBUTE_GROUPSET: _pointer_type_groupset,
    _geis_bindings.GEIS_EVENT_ATTRIBUTE_TOUCHSET: _pointer_type_touchset
}


def _attr_type_boolean(attr):
    """ Extracts an attribute value as a boolean.
    """
    return _geis_lib.geis_attr_value_to_boolean(attr)


def _attr_type_float(attr):
    """ Extracts an attribute value as a float.
    """
    geis_attr_value_to_float = _geis_lib.geis_attr_value_to_float
    geis_attr_value_to_float.restype = ctypes.c_float
    return geis_attr_value_to_float(attr)


def _attr_type_integer(attr):
    """ Extracts an attribute value as a integer.
    """
    return _geis_lib.geis_attr_value_to_integer(attr)


def _attr_type_pointer(attr):
    """ Extracts an attribute value as an object.
    """
    return _attr_pointer_type.get(_geis_attr_name(attr).decode('utf-8'),
                                  _pointer_type_unknown)(attr)


def _attr_type_string(attr):
    """ Extracts an attribute value as a string.
    """
    geis_attr_value_to_string = _geis_lib.geis_attr_value_to_string
    geis_attr_value_to_string.restype = ctypes.c_char_p
    return geis_attr_value_to_string(attr)


def _attr_type_unknown(attr):
    print("unknown attr type" + _geis_attr_name(attr).decode('utf-8'))
    return None


_attr_types = {
    _geis_bindings.GEIS_ATTR_TYPE_BOOLEAN:  _attr_type_boolean,
    _geis_bindings.GEIS_ATTR_TYPE_FLOAT:    _attr_type_float,
    _geis_bindings.GEIS_ATTR_TYPE_INTEGER:  _attr_type_integer,
    _geis_bindings.GEIS_ATTR_TYPE_POINTER:  _attr_type_pointer,
    _geis_bindings.GEIS_ATTR_TYPE_STRING:   _attr_type_string
}


def _cb_wrapper(ignored, eptr, context):
    """ A currying wrapper for event callbacks.

    This is a currying function to wrap a Python callback with arbitrary
    arguments so it can be invoked from a C callback.

    :param ignored: This argumenet is ignored.
    :param eptr: A C pointer to the internal GEIS event.
    :param context: A tuple containing the Geis class instance,
                    the Python callable, and the argument list.
    """
    (geis_instance, cb, args) = context
    cb(geis_instance, Event(eptr), args[0])


class Geis(object):
    """A GEIS API instance.
    """

    def __init__(self, *args):
        """Create a GEIS instance.

        This constructor takes a variable number of arguments (zero or more)
        all of he geis.GEIS_INIT_... form.

        On failure, an Exception is raised.
        """
        terminator = 0,
        va_args = args + terminator
        self._instance = _geis_new(*va_args)
        if self._instance == 0:
            raise GeisError('can not create GEIS instance')
        self._cb_wrapper =  _EventCallback(_cb_wrapper)
        self._class_curry = None
        self._device_curry = None
        self._event_curry = None

    def __del__(self):
        _geis_delete(self._instance)

    @property
    def _as_parameter_(self):
        return self._instance

    def get_configuration(self, item_name):
        """ Gets a named configuration value. """
        if (item_name == _geis_bindings.GEIS_CONFIGURATION_FD):
            fd = ctypes.c_long()
            status = _geis_get_configuration(self._instance,
                                             item_name.encode('utf-8'),
                                             ctypes.byref(fd))
            if status != _geis_bindings.GEIS_STATUS_SUCCESS:
                raise GeisError('error retrieving GEIS fd')
            return fd.value
        raise ValueError('unsupported config item name')

    def set_configuration(self, name, value):
        """ Sets a named configuration value. """
        raise ValueError('unsupported config item name')

    def register_class_callback(self, callback, *args):
        """ Registers a python callback to receive GEIS gesture class events.
        """
        context = self, callback, args
        self._class_curry = ctypes.py_object(context)
        _geis_register_class_callback(self._instance,
                                      self._cb_wrapper,
                                      self._class_curry)

    def register_device_callback(self, callback, *args):
        """ Registers a python callback to receive GEIS gesture device events.
        """
        context = self, callback, args
        self._device_curry = ctypes.py_object(context)
        _geis_register_device_callback(self._instance,
                                       self._cb_wrapper,
                                       self._device_curry)

    def register_event_callback(self, callback, *args):
        """ Registers a python callback to receive general GEIS events.
        """
        self._event_curry = ctypes.py_object((self, callback, args))
        _geis_register_event_callback(self._instance,
                                      self._cb_wrapper,
                                      self._event_curry)

    def dispatch_events(self):
        """ Pumps the geis event loop. """
        return _geis_dispatch_events(self._instance)

    def next_event(self):
        """ Pulls the next event, if any, off the geis event queue.

        :return: a geis.Event object
        :raise: geis.NoMoreEvents
        """
        event = Event()
        status = _geis_next_event(self._instance, event)
        if status not in [_geis_bindings.GEIS_STATUS_CONTINUE,
                          _geis_bindings.GEIS_STATUS_SUCCESS]:
            raise NoMoreEvents()
        return event


class Event(object):
    """ An event returned from the GEIS API.
    """

    def __init__(self, internal=ctypes.c_void_p()):
        self._event = internal
        
    @property
    def _as_parameter_(self):
        return ctypes.byref(self._event)

    def type(self):
        """ Gets the type of the event.
        """
        return _geis_event_type(self._event)

    def attrs(self):
        """ Gets the attributes associated with the event.
        """
        attr_list = {}
        for i in range(_geis_event_attr_count(self._event)):
            attr = _geis_event_attr(self._event, i)
            attr_name = _geis_attr_name(attr).decode('utf-8')
            attr_list[attr_name] = _attr_types.get(_geis_attr_type(attr),
                    _attr_type_unknown)(attr)
        return attr_list


class Filter(object):
    """ A Geis Filter object.
    """

    def __init__(self, geis, name):
        self._filter  = _geis_lib.geis_filter_new(geis, name.encode('utf-8'))

    def __del__(self):
        _geis_lib.geis_filter_delete(self._filter)

    @property
    def _as_parameter_(self):
        return self._filter

    def name(self):
        """ Gets the name of the filter.
        """
        return _geis_lib.geis_filter_name(self._filter)

    def add_term(self, facility, *terms):
        """ Adds a new term to the filter.

         :param facility: the filter facility to which the terms belong
         :param terms: a collection of (name, operation, value) tuples
        """
        for term in terms:
            if len(term) != 3:
                raise ValueError('invalid filter term')
            name, op, value = term
            _geis_lib.geis_filter_add_term(self._filter, facility,
                                           name.encode('utf-8'), op, value, 0)


class Subscription(object):
    """ A Geis subscription object.
    """

    def __init__(self, geis):
        """Constructs a GEIS subscription object.

        A subscription is a request to the gesture recognizer to receive gesture
        events.

        The default subscription is to receive all events from all devices for
        all regions.  The domain of the events received can be restructed
        through the use of filters.

        :param geis: The GEIS v2 instance.
        :raise: Exception
        """
        object.__init__(self)
        self._sub = _geis_subscription_new(geis, "py".encode('utf-8'), 0)
        self._filters = []

    def __del__(self):
        _geis_subscription_delete(self._sub)

    def activate(self):
        """ Activates the subscription.
        """
        _geis_subscription_activate(self._sub)

    def deactivate(self):
        """ Deactivates the subscription.
        """
        _geis_subscription_deactivate(self._sub)

    def name(self):
        """ Gets the name of the subscription.
        """
        return _geis_subscription_name(self._sub)

    def add_filter(self, filt):
        """Adds a filter to the subscription.

        :param filter: the filter to add
        """
        # keep a reference to the filter for Python doesn't garbage collect it
        if filt not in self._filters:
            self._filters.append(filt)
        _geis_lib.geis_subscription_add_filter(self._sub, filt)

    def remove_filter(self, filt):
        """ Removes a filter from the subscription.

         :param filter: the filter to remove
        """
        _geis_lib.geis_subscription_remove_filter(self._sub, filt)


