# -*- coding: utf-8 -*-
#
##########################################################################
# creole.server_reloader - Clean reload of CreoleServer
# Copyright © 2013 Pôle de compétences EOLE <eole@ac-dijon.fr>
#
# License CeCILL:
#  * in french: http://www.cecill.info/licences/Licence_CeCILL_V2-fr.html
#  * in english http://www.cecill.info/licences/Licence_CeCILL_V2-en.html
##########################################################################

"""This module provide cherrypy plugins.

"""

import pyinotify
from cherrypy.process.plugins import SimplePlugin

class InotifyMonitor(SimplePlugin):
    """Execute a handler on inotify events.
    
    The handler must be a subclass of
    :class:`pyinotify.ProcessHandler`.

    Watched files/directories can be added with
    :class:`pyinotify.WatchManager` API accessible through
    :meth:`InotifyMonitor.watch()`

    Example::

    >>> from pyinotify import PrintAllEvents, ALL_EVENTS
    >>> from creole.cherrypy.plugins import InotifyMonitor
    >>> engine = cherrypy.engine
    >>> monitor = InotifyMonitor(engine, PrintAllEvents())
    >>> descriptor = monitor.watch.add('/tmp', ALL_EVENTS)

    """

    watch = None
    """Inotify watch manager.

    """

    def __init__(self, bus, inotifyHandler):
        if not isinstance(inotifyHandler, pyinotify.ProcessEvent):
            msg = 'inotifyHandler not an instance of pyinotify.ProcessEvent'
            raise TypeError(msg)

        self._inotifyHandler = inotifyHandler
        self.watch = pyinotify.WatchManager()
        self._notifier = pyinotify.ThreadedNotifier(self.watch,
                                                    self._inotifyHandler)
        SimplePlugin.__init__(self, bus)


    def start(self):
        """Start our own background pyinotify thead."""
        self.bus.log('Start InotifyMonitor thread')
        self._notifier.start()
    start.priority = 70


    def stop(self):
        """Stop inotify thread.

        """
        self.bus.log('Stop InotifyMonitor thread')
        self._notifier.stop()


    def graceful(self):
        """Restart the notifier

        """
        self.stop()
        self.start()
