# coding=utf-8
__author__ = "AstroPrint Product Team <product@astroprint.com>"
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2017 3DaGoGo, Inc - Released under terms of the AGPLv3 License"

import logging
from octoprint.events import eventManager

class PluginService(object):
	_validEvents = []

	def __init__(self):
		self._eventSubscribers = {}
		self._logger = logging.getLogger('PluginService::%s' % self.__class__.__name__)
		self._eventManager = eventManager()

	# Subscribe to a service event(s)
	#
	# - events: the event name or an array of event names
	# - callback: The handler for the event. It will receive the following parameters:
	#					- event: Event name
	#					- data: a hash with data (defined per event)
	def subscribe(self, events, callback):
		if isinstance(events, basestring):
			events = [events]

		for e in events:
			if e in self._validEvents:
				if e in self._eventSubscribers:
					if callback not in self._eventSubscribers[e]:
						self._eventSubscribers[e].add(callback)
				else:
					self._eventSubscribers[e] = set([callback])

	# Unsubscribe from a service event
	#
	# - events: the event name or an array of event names
	# - callback: the callback used when registering.
	def unsubscribe(self, events, callback):
		if isinstance(events, basestring):
			events = [events]

		for e in events:
			if e in self._eventSubscribers:
				#discard does not raise if the element doesn't exist
				self._eventSubscribers[e].discard(callback)
				if not bool(self._eventSubscribers[e]):
					del self._eventSubscribers[e]

	# Publish an event to subscribers
	#
	# - event: Event name
	# - data: Data to be passed to the event
	def publishEvent(self, event, data= None):
		if event in self._validEvents:
			handlers = self._eventSubscribers.get(event)
			if handlers:
				for h in handlers:
					try:
						h(event, data)
					except:
						self._logger.error('Problem publishing event', exc_info= True)

@@ -271,16 +271,29 @@
 logging%0A
+import time%0A%0A
 from oct
@@ -833,32 +833,42 @@
 events, callback
+, freq=0.0
 ):%0A%09%09if isinstan
@@ -1085,24 +1085,25 @@
 %5Be%5D.add(
+%5B
 callback
 )%0A%09%09%09%09el
@@ -1090,24 +1090,37 @@
 dd(%5Bcallback
+, freq, None%5D
 )%0A%09%09%09%09else:%0A
@@ -1156,12 +1156,9 @@
 %5D = 
-set(
+%5B
 %5Bcal
@@ -1162,18 +1162,29 @@
 callback
+,freq, None%5D
 %5D
-)
 %0A%0A%09# Uns
@@ -1902,24 +1902,46 @@
 f handlers:%0A
+%09%09%09%09now = time.time()%0A
 %09%09%09%09for h in
@@ -1937,16 +1937,19 @@
 %09%09%09for h
+dlr
  in hand
@@ -1963,13 +1963,131 @@
 %09%09%09%09
-try:%0A
+h = hdlr%5B0%5D%0A%09%09%09%09%09f = hdlr%5B1%5D%0A%09%09%09%09%09last = hdlr%5B2%5D%0A%09%09%09%09%09if last is None or now - last %3E= f:%0A%09%09%09%09%09%09try:%0A%09%09%09%09%09%09%09hdlr%5B2%5D = now%0A%09
 %09%09%09%09
@@ -2112,16 +2112,17 @@
 %09%09%09%09
+%09
 except:%0A
 %09%09%09%09
@@ -2117,16 +2117,17 @@
 except:%0A
+%09
 %09%09%09%09%09%09se

event fréquence