WITH range_alarm_events AS (
	SELECT *,
        /* Get the last time this event was active within the given time range*/
        (
          /* Search for the clear event (if exists) for the outer query's active event */ 
		  SELECT MIN(eventtime)
		  FROM alarm_events e2
		  WHERE e2.eventid = e.eventid /* eventid is unique per alarm instance */
			AND e2.eventtime >= e.eventtime
			AND e2.eventtype = 1 /* Look only for the clear event */
		  ORDER BY eventtime ASC
          LIMIT 1
		) AS endtime
    FROM alarm_events e
    /* The range for both start/end allows for index optimizations */
    WHERE eventtime BETWEEN :startDate AND :endDate
	  /* Filter out system events */
	  AND eventflags & 1 != 1
	  /* Filter priority */
	  AND priority >= :priority
      /* Filter for Active events */
      AND eventtype = 0
	ORDER BY eventtime DESC
    LIMIT 2000
), range_alarm_events2 AS (
	SELECT *,
	       LEAST(COALESCE(endtime, NOW()), :endDate) AS endtime_est, /* Clamp to end of time range if clear event is after end time */
           TIMESTAMPDIFF(SECOND, eventtime, LEAST(COALESCE(endtime, NOW()), :endDate)) AS duration
    FROM range_alarm_events
)
SELECT e.id,
  e.eventtime AS starttime, e.endtime,
  /* Translate duration to a string */
  CAST(SEC_TO_TIME(FLOOR(e.duration)) AS CHAR) AS duration,
  /* Retrieve data */
  ddevice.strvalue AS device,
  displaypath AS description,
  e.source,
  /* Translate priority to string */
  dclass.strvalue AS class,
  CASE
    WHEN e.priority=4 THEN "Critical"
    WHEN e.priority=3 THEN "High"
    WHEN e.priority=2 THEN "Medium"
    WHEN e.priority=1 THEN "Low"
    WHEN e.priority=0 THEN "Diagnostic"
    ELSE "N/A"
  END AS priority,
  /* Retrieve PLCTag */
  dtag.strvalue AS plctag
FROM range_alarm_events2 e
/* Lookup PLCTag */
JOIN alarm_event_data dtag ON e.id = dtag.id AND dtag.propname = "PLCTag"
/* Lookup Device */
JOIN alarm_event_data ddevice ON e.id = ddevice.id AND ddevice.propname = "Device"
/* Lookup Class */
JOIN alarm_event_data dclass ON e.id = dclass.id AND dclass.propname = "Class"
WHERE CASE
		WHEN dclass.strvalue = "Error" THEN 2
		WHEN dclass.strvalue = "Warning" THEN 1
		WHEN dclass.strvalue = "Message" THEN 0
	  END >= :class;