WITH range_alarm_events AS (
	SELECT e.*,
        /* 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
      /* Filter for Active events */
      eventtype = 0
	  /* Filter priority */
	  AND priority >= :priority
      /* Filter by tag */
      AND source LIKE CONCAT("prov:default:/tag:", REGEXP_REPLACE(:tagPath, "\\[.*\\]|\\/Graphics", ""), "%")
	ORDER BY eventtime DESC
    LIMIT 50
), range_alarm_events2 AS (
	SELECT *,
	       COALESCE(endtime, NOW()) AS endtime_est, /* Clamp to end of time range if clear event is after end time */
           TIMESTAMPDIFF(SECOND, eventtime, COALESCE(endtime, NOW())) 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";