- alias: PMG - BT Event Handler
  id: "36f10a58-2c57-4a7a-8bd7-b5472d9d7ac0"
  triggers:
    - trigger: state
      entity_id: sensor.pmg_lucy_connected
      id: lucy_state
    - trigger: state
      entity_id: sensor.pmg_nessie_connected
      id: nessie_state
    - trigger: event
      event_type: timer.finished
      event_data:
        entity_id: timer.pmg_end_lucy
      id: lucy_timer
    - trigger: event
      event_type: timer.finished
      event_data:
        entity_id: timer.pmg_end_nessie
      id: nessie_timer
  conditions: []
  variables:
    entity_map:
      lucy:
        binary_sensor: binary_sensor.pmg_stats_lucy
        current: sensor.pmg_current_lucy
        timer: timer.pmg_end_lucy
        connected: sensor.pmg_lucy_connected
      nessie:
        binary_sensor: binary_sensor.pmg_stats_nessie
        current: sensor.pmg_current_nessie
        timer: timer.pmg_end_nessie
        connected: sensor.pmg_nessie_connected
    acc: "{{ iif(trigger.id in ['lucy_state','lucy_timer'], 'lucy', 'nessie') }}"
    binary: "{{ entity_map[acc].binary_sensor }}"
    current: "{{ entity_map[acc].current }}"
    timer: "{{ entity_map[acc].timer }}"
    connected: "{{ entity_map[acc].connected }}"
    nickname: "{{ iif(acc == 'lucy', 'Lucy', 'Nessie') }}"
  mode: parallel
  max: 4

  actions:
    - variables:
        is_con: "{{ is_state(connected, 'True') }}"
        is_rec: "{{ is_state(binary, 'on') }}"

    - choose:
        - alias: "Start Session on connect"
          conditions:
            - condition: template
              value_template: "{{ trigger.to_state.state == 'True' and trigger.id in ['nessie_state','lucy_state'] }}"
          sequence:
            - alias: Set session active
              action: variable.update_binary_sensor
              target:
                entity_id: "{{ binary }}"
              data:
                value: "true"
            - alias: Cancel end timer
              action: timer.cancel
              target:
                entity_id: "{{ timer }}"
            - alias: Set state to rec
              action: variable.update_sensor
              target:
                entity_id: "{{ current }}"
              data:
                value: "rec"
        - alias: "Start timer + pause on disconnect"
          conditions:
            - condition: template
              value_template: "{{ is_state(binary, 'on') and trigger.to_state.state == 'False' and trigger.id in ['nessie_state','lucy_state'] }}"
          sequence:
            - alias: Start end timer
              action: timer.start
              target:
                entity_id: "{{ timer }}"
            - alias: Set state to paused
              action: variable.update_sensor
              target:
                entity_id: "{{ current }}"
              data:
                value: "paused"

        - alias: "End session on timer finished"
          conditions:
            - condition: template
              value_template: "{{ trigger.id in ['lucy_timer','nessie_timer'] }}"
          sequence:
            - alias: Set session inactive
              action: variable.update_binary_sensor
              target:
                entity_id: "{{ binary }}"
              data:
                value: "false"
            - alias: Set state to paused
              action: variable.update_sensor
              target:
                entity_id: "{{ current }}"
              data:
                value: "idle"

- alias: PMG - Start Session
  id: "52239269-a20d-41a4-82a3-2b6d9983d18f"
  variables:
    account_map:
      binary_sensor.pmg_stats_lucy: lucy
      binary_sensor.pmg_stats_nessie: nessie
    entity_map:
      lucy:
        binary_sensor: binary_sensor.pmg_stats_lucy
        session_select: select.pmg_session_lucy
        current: sensor.pmg_current_lucy
        notify: notify.mobile_app_lucys_mi_9
        timer_loop: script.pmg_lucy_timer_loop
      nessie:
        binary_sensor: binary_sensor.pmg_stats_nessie
        session_select: select.pmg_session_nessie
        current: sensor.pmg_current_nessie
        notify: notify.mobile_app_lucy_s_phone
        timer_loop: script.pmg_nessie_timer_loop
    acc: "{{ account_map[trigger.entity_id] }}"
    binary: "{{ entity_map[acc].binary_sensor }}"
    current: "{{ entity_map[acc].current }}"
    notify: "{{ entity_map[acc].notify }}"
    select: "{{ entity_map[acc].session_select }}"
    nickname: "{{ iif(acc=='lucy','Lucy','Nessie') | string }}"
    timer_loop: "{{ entity_map[acc].timer_loop }}"
  triggers:
    - entity_id:
        - binary_sensor.pmg_stats_lucy
        - binary_sensor.pmg_stats_nessie
      id: toggle
      trigger: state
      from:
        - "off"
        - "off"
      to:
        - "on"
        - "on"
  conditions: []
  actions:
    - target:
        entity_id: "{{ current }}"
      data:
        value: "rec"
        attributes:
          Start: "{{ now().timestamp() | round(0) }}"
          Duration: 0
          Catched: 0
          Escaped: 0
          Spins: 0
          Items: 0
          CatchRate: 0
          SpinRate: 0
          CatchRatio: 0
          ItemRatio: 0
      action: variable.update_sensor
    - action: "{{ notify }}"
      data:
        title: "🚀 Let's GO & catch 'em all, : {{nickname}} <~ 🎯!"
        message: "🔴 Rec. started! <i>Happy catchin'!</i> 🦊"
        data:
          persistent: "true"
          sticky: "true"
          tag: "pmg_session_{{acc}}"
          group: "pmg_{{acc}}"
          priority: "high"
          ttl: 0
          visibility: public
    - action: script.turn_on
      target:
        entity_id: "{{ timer_loop }}"
  mode: queued
  max: 2
- alias: PMG - Notification Event Handler
  id: "5b6cd7a1-0560-402a-8c5a-91f42dd60211"
  variables:
    account_map:
      sensor.lucy_s_phone_last_notification: nessie
      sensor.lucys_mi_9_last_notification: lucy
    entity_map:
      lucy:
        binary_sensor: binary_sensor.pmg_stats_lucy
        current: sensor.pmg_current_lucy
        duration: sensor.pmg_lucy_live_duration
      nessie:
        binary_sensor: binary_sensor.pmg_stats_nessie
        current: sensor.pmg_current_nessie
        duration: sensor.pmg_nessie_live_duration
    acc: "{{ account_map[trigger.entity_id] }}"
    binary: "{{ entity_map[acc].binary_sensor }}"
    current: "{{ entity_map[acc].current }}"
    duration: "{{ entity_map[acc].duration }}"
    source: "{{ trigger.entity_id }}"
  triggers:
    - entity_id:
        - sensor.lucy_s_phone_last_notification
        - sensor.lucys_mi_9_last_notification
      trigger: state
  conditions:
    - condition: template
      value_template: >
        {{ is_state(binary,'on') and state_attr(trigger.entity_id, 'android.title') == "Zusatzgerät" }}
  actions:
    - variables:
        Duration: >-
          {% set return_val = duration %}
          {{ return_val | int(default=0) }}
        Catched: >-
          {{ iif(state_attr(source, 'android.text') == "Du hast ein Pokémon gefangen!", (state_attr(current,'Catched') | int) + 1, state_attr(current,'Catched')) | int }}
        Escaped: >-
          {{ iif(state_attr(source, 'android.text') == "Das Pokémon ist geflohen!", (state_attr(current,'Escaped') | int) + 1, state_attr(current,'Escaped')) | int }}
        itemcount: >-
          {% set text = state_attr(source, 'android.text') %}
          {% set found = text | regex_findall('(\d+)\s+Items', ignorecase=True) %}
          {{ (found[0] | int) if found else 0 }}
        Items: >-
          {% if itemcount > 0 %}
            {{ (state_attr(current,'Items') | int) + itemcount }}
          {% else %}
            {{ state_attr(current,'Items') | int }}
          {% endif %}
        Spins: >-
          {% if itemcount > 0 %}
            {{ (state_attr(current,'Spins') | int) + 1 }}
          {% else %}
            {{ state_attr(current,'Spins') | int }}
          {% endif %}
        CatchRate: >-
          {% if Duration | int >= 60 %}
            {{ ((Catched | int) / ((Duration | int) / 60)) | round(2) }}
          {% else %}
            {{ Catched | int }}
          {% endif %}
        SpinRate: >-
          {% if Duration | int >= 60 %}
            {{ ((Spins | int) / ((Duration | int) / 60)) | round(2) }}
          {% else %}
            {{ Spins | int }}
          {% endif %}
        CatchRatio: >-
          {% if Escaped | int > 0 %}
            {{ ((Catched | int) / (Escaped | int)) | round(2) }}
          {% else %}
            {{ Catched | int }}
          {% endif %}
        ItemRatio: >-
          {% if Spins | int > 0 %}
            {{ ((Items | int) / (Spins | int)) | round(2) }}
          {% else %}
            0
          {% endif %}
    - target:
        entity_id: "{{ current }}"
      data:
        replace_attributes: false
        value: "rec"
        attributes:
          Duration: "{{ (Duration | int) }}"
          Catched: "{{ (Catched | int) }}"
          Escaped: "{{ (Escaped | int) }}"
          Spins: "{{ (Spins | int) }}"
          Items: "{{ (Items | int) }}"
          CatchRate: "{{ (CatchRate | float) }}"
          SpinRate: "{{ (SpinRate | float) }}"
          CatchRatio: "{{ (CatchRatio | float) }}"
          ItemRatio: "{{ (ItemRatio | float) }}"
      action: variable.update_sensor
  mode: queued
  max: 10
- alias: PMG - Notify on Updates
  id: "ed485bc0-d294-4826-97e1-c503ee2e0956"
  variables:
    acc: "{{trigger.id}}"
    nickname: "{{ iif(acc=='lucy','Lucy','Nessie') | string }}"
    entity_map:
      lucy:
        binary: binary_sensor.pmg_stats_lucy
        current: sensor.pmg_current_lucy
        notify: notify.mobile_app_lucys_mi_9
        timer: timer.pmg_notify_lucy
        duration: sensor.pmg_lucy_live_duration
      nessie:
        binary: binary_sensor.pmg_stats_nessie
        current: sensor.pmg_current_nessie
        notify: notify.mobile_app_lucy_s_phone
        timer: timer.pmg_notify_nessie
        duration: sensor.pmg_nessie_live_duration
    binary: "{{entity_map[acc].binary}}"
    current: "{{entity_map[acc].current}}"
    notify: "{{entity_map[acc].notify}}"
    timer: "{{entity_map[acc].timer}}"
    duration: "{{entity_map[acc].duration}}"
  triggers:
    - trigger: event
      event_type: timer.finished
      event_data:
        entity_id: timer.pmg_notify_lucy
      id: lucy
    - trigger: event
      event_type: timer.finished
      event_data:
        entity_id: timer.pmg_notify_nessie
      id: nessie
  conditions: []
  actions:
    - alias: "Notifier"
      action: "{{ notify }}"
      data:
        title: >-
          {% set pool = ["catchin'! 🦊", "throwin'! 🎯", "scoutin'! 🔎", "flowin'! 🚀"] %}
          🔴 {{nickname}}’s {{ pool | random }} (⏱ {{ state_attr(duration,'pretty') }} )
        message: |-
          🎯: <b><span color="green">{{ state_attr(current,'Catched') }}</span></b> | 🏃‍♂️: <b><span color="red">{{ state_attr(current,'Escaped') }}</span></b> | 📊: <b>{{ state_attr(current,'CatchRate') }}</b>/min | ⚖️: <b>{{ state_attr(current,'CatchRatio') }}:1</b>
        data:
          persistent: "true"
          sticky: "true"
          tag: "pmg_session_{{acc}}"
          group: "pmg_{{acc}}"
          priority: "high"
          ttl: 0
          visibility: public
  mode: queued
  max: 10

- alias: PMG - End Session
  id: "8e114df9-fba9-4472-b5f2-af81a27a8a07"
  variables:
    account_map:
      binary_sensor.pmg_stats_lucy: lucy
      binary_sensor.pmg_stats_nessie: nessie
    entity_map:
      lucy:
        binary_sensor: binary_sensor.pmg_stats_lucy
        session_select: select.pmg_session_lucy
        current: sensor.pmg_current_lucy
        notify: notify.mobile_app_lucys_mi_9
        duration: sensor.pmg_lucy_live_duration
      nessie:
        binary_sensor: binary_sensor.pmg_stats_nessie
        session_select: select.pmg_session_nessie
        current: sensor.pmg_current_nessie
        notify: notify.mobile_app_lucy_s_phone
        duration: sensor.pmg_nessie_live_duration
    acc: "{{ account_map[trigger.entity_id] }}"
    binary: "{{ entity_map[acc].binary_sensor }}"
    total: "{{ entity_map[acc].total }}"
    current: "{{ entity_map[acc].current }}"
    notify: "{{ entity_map[acc].notify }}"
    select: "{{ entity_map[acc].session_select }}"
    duration: "{{ entity_map[acc].duration }}"
    nickname: "{{ iif(acc=='lucy','Lucy','Nessie') | string }}"
  triggers:
    - trigger: state
      entity_id:
        - binary_sensor.pmg_stats_lucy
        - binary_sensor.pmg_stats_nessie
      from: "on"
      to: "off"
      id: toggle
  conditions: []
  actions:
    - alias: Turn binary sensor off
      target:
        entity_id: "{{ binary }}"
      data:
        replace_attributes: false
        attributes:
          Session:
            Id: >-
              {% set list = state_attr(binary, 'Session').Id %}
              {% set add = [list|count] %}
              {{ flatten([list, add]) }}
            Start: >-
              {% set list = state_attr(binary, 'Session').Start %}
              {% set add = [state_attr(current,'Start')] %}
              {{ flatten([list, add]) }}
            End: >-
              {% set list = state_attr(binary, 'Session').End %}
              {% set add = [now().timestamp()] %}
              {{ flatten([list, add]) }}
            Duration: >-
              {% set list = state_attr(binary, 'Session').Duration %}
              {% set Start = state_attr(current,'Start') | float %}
              {% set Duration = (now().timestamp() - Start) | round(0) %}
              {% set add = [Duration] %}
              {{ flatten([list, add]) }}
            Catched: >-
              {% set list = state_attr(binary, 'Session').Catched %}
              {% set add = [state_attr(current,'Catched')] %}
              {{ flatten([list, add]) }}
            Escaped: >-
              {% set list = state_attr(binary, 'Session').Escaped %}
              {% set add = [state_attr(current,'Escaped')] %}
              {{ flatten([list, add]) }}
            Items: >-
              {% set list = state_attr(binary, 'Session').Items %}
              {% set add = [state_attr(current,'Items')] %}
              {{ flatten([list, add]) }}
            Spins: >-
              {% set list = state_attr(binary, 'Session').Spins %}
              {% set add = [state_attr(current,'Spins')] %}
              {{ flatten([list, add]) }}
            CatchRate: >-
              {% set list = state_attr(binary, 'Session').CatchRate %}
              {% set add = [state_attr(current,'CatchRate')] %}
              {{ flatten([list, add]) }}
            SpinRate: >-
              {% set list = state_attr(binary, 'Session').SpinRate %}
              {% set add = [state_attr(current,'SpinRate')] %}
              {{ flatten([list, add]) }}
            CatchRatio: >-
              {% set list = state_attr(binary, 'Session').CatchRatio %}
              {% set add = [state_attr(current,'CatchRatio')] %}
              {{ flatten([list, add]) }}
            ItemRatio: >-
              {% set list = state_attr(binary, 'Session').ItemRatio %}
              {% set add = [state_attr(current,'ItemRatio')] %}
              {{ flatten([list, add]) }}
      action: variable.update_binary_sensor

    - alias: Set current sensor to idle
      action: variable.update_sensor
      target:
        entity_id: "{{ current }}"
      data:
        value: "idle"
    - alias: Final notification
      action: "{{ notify }}"
      data:
        title: "💤 {{nickname}} is takin' a nap! 🌃"
        message: >-
          ✅ Done after ⏱ {{ state_attr(duration, 'pretty') }} 🔚.
          🏁 {{nickname}}'s Results: 🎯: <b><span color="green">{{ state_attr(current,'Catched') }}</span></b> | 🏃‍♂️: <b><span color="red">{{ state_attr(current,'Escaped') }}</span></b> | 📊: <b>{{ state_attr(current,'CatchRate') }}</b>/min | ⚖️: <b>{{ state_attr(current,'CatchRatio') }}:1</b>
        data:
          persistent: "true"
          sticky: "true"
          tag: "pmg_session_{{acc}}"
          group: "pmg_{{acc}}"
          priority: "high"
          ttl: 30
          visibility: public

    - delay:
        seconds: 3

    - alias: Select first entry
      action: select.select_first
      target:
        entity_id: "{{ select }}"
  mode: parallel
