##
# See the file COPYRIGHT for copyright information.
#
# 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.
##

"""
HTML5 EventSource support.
"""

from collections import deque
from time import time

from zope.interface import implementer
from twisted.logger import Logger, ILogObserver

from ..data.model import Incident
from ..data.json import textFromJSON



class Event(object):
    """
    HTML5 EventSource event.
    """
    def __init__(self, message, eventID=None, eventClass=None, retry=None):
        self.message    = message
        self.eventID    = eventID
        self.eventClass = eventClass
        self.retry      = retry


    def render(self):
        parts = []

        if self.eventID is not None:
            parts.append(u"id: {0}".format(self.eventID))

        if self.eventClass is not None:
            parts.append(u"event: {0}".format(self.eventClass))

        if self.retry is not None:
            parts.append(u"retry: {0:d}".format(self.retry))

        parts.extend(
            u"data: {}".format(line) for line in self.message.split(u"\n")
        )

        return (u"\r\n".join(parts) + u"\r\n\r\n")



@implementer(ILogObserver)
class DataStoreEventSourceLogObserver(object):
    """
    Observer for events related to any updates to the data store.
    """
    log = Logger()


    def __init__(self):
        self._listeners = set()
        self._events = deque(maxlen=1000)
        self._start = time()
        self._counter = 0


    def addListener(self, listener, lastEventID=None):
        self.log.debug("Adding listener: {listener}", listener=listener)

        self._playback(listener, lastEventID)

        self._listeners.add(listener)


    def removeListener(self, listener):
        self.log.debug("Removing listener: {listener}", listener=listener)

        self._listeners.add(listener)


    def _transmogrify(self, loggerEvent):
        """
        Convert a logger event into an EventSource event.
        """
        if "storeWriteClass" not in loggerEvent:
            # Not a data store event
            return None

        eventClass = loggerEvent.get("storeWriteClass", None)

        if eventClass is None:
            return

        elif eventClass is Incident:
            incident = loggerEvent.get("incident", None)

            if incident is None:
                incidentNumber = loggerEvent.get("incidentNumber", None)
            else:
                incidentNumber = incident.number

            self.log.critical(
                "Unable to determine incident number from store event: {event}",
                event=loggerEvent,
            )

            message = dict(incident_number=incidentNumber)

        else:
            self.log.debug(
                "Unknown data store event class: {eventClass}",
                eventClass=eventClass
            )
            return

        eventSourceEvent = Event(
            # FIXME: add ID
            eventClass=eventClass.__name__,
            message=textFromJSON(message),
        )
        return eventSourceEvent


    def _playback(self, listener, lastEventID):
        if lastEventID is None:
            return

        observerID, counter = lastEventID.split(":")

        if observerID != str(id(self)):
            # lastEventID came from a different observer
            counter = 0

        for eventCounter, event in self.events:
            if eventCounter >= counter:
                listener.write(event.render().encode("utf-8"))


    def _publish(self, eventSourceEvent):
        eventText = eventSourceEvent.render().encode("utf-8")

        for listener in self._listeners:
            listener.write(eventText)

        self._counter += 1
        self._events.append((self._counter, eventSourceEvent))


    def __call__(self, event):
        eventSourceEvent = self._transmogrify(event)
        if eventSourceEvent is None:
            return

        self._publish(eventSourceEvent)

@@ -2371,27 +2371,36 @@
  loggerEvent
+, eventID
 ):%0A
-
         %22%22%22%0A
@@ -2963,16 +2963,59 @@
 number%0A%0A
+            if incidentNumber is None:%0A    
         
@@ -3037,16 +3037,20 @@
 itical(%0A
+    
         
@@ -3112,16 +3112,39 @@
  event: 
+%22%0A                    %22
 %7Bevent%7D%22
@@ -3141,24 +3141,28 @@
  %22%7Bevent%7D%22,%0A
+    
             
@@ -3188,33 +3188,60 @@
 nt,%0A            
+  
-)
+  )%0A                return
 %0A%0A            me
@@ -3514,23 +3514,24 @@
     
-# FIXME: add 
+eventID=event
 ID
+,
 %0A   
@@ -4122,24 +4122,33 @@
 tSourceEvent
+, eventID
 ):%0A        e
@@ -4285,35 +4285,8 @@
 t)%0A%0A
-        self._counter += 1%0A
     
@@ -4373,24 +4373,52 @@
 lf, event):%0A
+        self._counter += 1%0A%0A
         even
@@ -4456,16 +4456,31 @@
 fy(event
+, self._counter
 )%0A      
@@ -4522,32 +4522,32 @@
         return%0A%0A
-
         self._pu
@@ -4568,10 +4568,25 @@
 rceEvent
+, self._counter
 )%0A

Add event ID