/*+ MAX_EXECUTION_TIME(8000) */

-- CORRECT APPROACH: Active alarm = latest event per eventid is eventtype=0
-- Ignition alarm lifecycle: 0=activated, 1=cleared, 2=acknowledged
-- If latest event is type 0, alarm is active

SELECT
  ae.id AS ID,
  ae.eventtime AS StartTimestamp,
  TIME_FORMAT(SEC_TO_TIME(TIMESTAMPDIFF(SECOND, ae.eventtime, NOW())), '%H:%i:%s') AS Duration,
  CONCAT(REPLACE(ae.displaypath, '_', '-'), ' ', SUBSTRING_INDEX(ae.source, ':/alm:', -1)) AS Description,

  CASE ae.priority
    WHEN 0 THEN 'Diagnostic' 
    WHEN 1 THEN 'Low' 
    WHEN 2 THEN 'Medium'
    WHEN 3 THEN 'High' 
    WHEN 4 THEN 'Critical' 
    ELSE 'Unknown'
  END AS Priority,

  IFNULL(tag.strValue, '') AS Tag,
  
  -- Use myLocation property directly (99.96% coverage) - MUCH faster than parsing tags!
  IFNULL(loc.strValue, '') AS Location,
  
  CASE 
    WHEN ae.priority = 3 THEN 'Alarms-Styles/High'
    WHEN ae.priority = 2 THEN 'Alarms-Styles/Medium'
    WHEN ae.priority = 1 THEN 'Alarms-Styles/Low'
    WHEN ae.priority = 0 THEN 'Alarms-Styles/Diagnostic'
    ELSE 'Alarms-Styles/NoAlarm'
  END AS Style

FROM alarm_events ae
INNER JOIN (
  -- Find latest event per eventid, then filter where it's type 0 (active)
  -- Ignition alarm pattern: latest event type 0 = active, type 1/2 = cleared/ack
  SELECT lat.eventid, lat.latest_id
  FROM (
    SELECT eventid, MAX(id) as latest_id
    FROM alarm_events
    WHERE eventid IS NOT NULL
    GROUP BY eventid
  ) lat
  INNER JOIN alarm_events latest_event ON latest_event.id = lat.latest_id
  WHERE latest_event.eventtype = 0
    AND latest_event.displaypath NOT LIKE '%System Startup%'
    AND latest_event.source NOT LIKE '%System Startup%'
    AND latest_event.displaypath NOT LIKE '%System Shutdown%'
    AND latest_event.source NOT LIKE '%System Shutdown%'
) active ON ae.id = active.latest_id
LEFT JOIN alarm_event_data tag FORCE INDEX (idx_alarm_event_data_lookup)
  ON tag.id = ae.id AND tag.propname = 'myTag'
LEFT JOIN alarm_event_data loc FORCE INDEX (idx_alarm_event_data_lookup)
  ON loc.id = ae.id AND loc.propname = 'myLocation'

WHERE 
  -- Priority filter: Only evaluate priority conditions when parameter is provided
  (
       :priority IS NULL OR :priority = '' OR :priority = 0
    OR (
      :priority IS NOT NULL AND :priority != '' AND :priority != 0 AND (
        (:priority = 3 AND ae.priority = 3)
    OR (:priority = 2 AND ae.priority BETWEEN 2 AND 3)
    OR (:priority = 1 AND ae.priority BETWEEN 1 AND 3)
      )
    )
  )

  -- Location filter: Use myLocation property directly (much faster than parsing tags!)
  AND (
       :location IS NULL OR :location = ''
    OR (
      :location IS NOT NULL AND :location != '' AND
      IFNULL(loc.strValue, '') LIKE CONCAT('%', :location, '%')
    )
  )

ORDER BY ae.eventtime DESC;
