###############################################################################
# PACKAGE: Lounge IR Remote Functions
# VERSION: 1.0 - 2026-05-05
#
# PURPOSE:
# - Listen for Tasmota IR receive events over MQTT.
# - Convert known IR hash values into lounge scene commands or toggle actions.
# - Throttle repeated button-hold messages so toggles do not flip repeatedly.
#
# MQTT SOURCE:
# - Topic: tele/tasmo-ytfir-a25e21-lounge-1/RESULT
# - JSON path: IrReceived.Hash
#
# NOTES:
# - The incoming hash is normalised to lowercase before matching.
# - Adjust input_number.lounge_ir_remote_throttle_seconds if button repeats
#   are still too fast or feel too slow.
###############################################################################

input_text:
  lounge_ir_remote_last_hash:
    name: "Lounge IR Remote Last Hash"
    max: 32

input_datetime:
  lounge_ir_remote_last_seen:
    name: "Lounge IR Remote Last Seen"
    has_date: true
    has_time: true

input_number:
  lounge_ir_remote_throttle_seconds:
    name: "Lounge IR Remote Throttle Seconds"
    min: 0.2
    max: 10
    step: 0.1
    mode: box
    unit_of_measurement: "s"
    initial: 1.5

automation:
  - id: lounge_ir_remote_functions
    alias: "Lounge IR Remote Functions"
    description: >
      Handles lounge IR remote hash commands from the Tasmota IR receiver.
    mode: queued
    max: 20
    max_exceeded: silent

    triggers:
      - trigger: mqtt
        topic: "tele/tasmo-ytfir-a25e21-lounge-1/RESULT"

    variables:
      ir_hash: >-
        {{ trigger.payload_json.get('IrReceived', {}).get('Hash', '') | string | lower }}
      scene_map:
        "0xe23b4151": "Bright"
        "0xce5541e4": "TV General"
        "0xc0c52aff": "Movie"
        "0x79fb9e54": "Reading On/Off"
      toggle_hashes:
        - "0x2b4da162"
        - "0xc2997ec2"

    conditions:
      - condition: template
        value_template: "{{ ir_hash in scene_map or ir_hash in toggle_hashes }}"

    actions:
      - alias: "Stop repeated button-hold messages"
        choose:
          - conditions:
              - condition: template
                value_template: >-
                  {{
                    ir_hash == states('input_text.lounge_ir_remote_last_hash')
                    and
                    (
                      as_timestamp(now())
                      - as_timestamp(states('input_datetime.lounge_ir_remote_last_seen'), 0)
                    )
                    < (states('input_number.lounge_ir_remote_throttle_seconds') | float(1.5))
                  }}
            sequence:
              - stop: "Repeated IR hash ignored by throttle."

      - alias: "Store this IR hash and timestamp for throttle checking"
        action: input_text.set_value
        target:
          entity_id: input_text.lounge_ir_remote_last_hash
        data:
          value: "{{ ir_hash }}"

      - alias: "Store current timestamp for throttle checking"
        action: input_datetime.set_datetime
        target:
          entity_id: input_datetime.lounge_ir_remote_last_seen
        data:
          datetime: "{{ now().strftime('%Y-%m-%d %H:%M:%S') }}"

      - alias: "Run the matching lounge command"
        choose:
          - alias: "Scene commands"
            conditions:
              - condition: template
                value_template: "{{ ir_hash in scene_map }}"
            sequence:
              - action: script.lounge_set_scene
                data:
                  scene_name: "{{ scene_map[ir_hash] }}"

          - alias: "Toggle Rinnai gas heater"
            conditions:
              - condition: template
                value_template: "{{ ir_hash == '0x2b4da162' }}"
            sequence:
              - variables:
                  currently_on: "{{ is_state('switch.rinnai_neo_gas_heater_heater_operation', 'on') }}"
              - variables:
                  new_state_text: "{{ 'Off' if currently_on else 'On' }}"

              - choose:
                  - conditions:
                      - condition: template
                        value_template: "{{ currently_on }}"
                    sequence:
                      - action: switch.turn_off
                        target:
                          entity_id: switch.rinnai_neo_gas_heater_heater_operation
                default:
                  - action: switch.turn_on
                    target:
                      entity_id: switch.rinnai_neo_gas_heater_heater_operation

              - action: script.view_road_announcement
                data:
                  channels: "sony_tv_lounge"
                  title: "View Road"
                  short_announcement: "Rinnai Gas Heater"
                  long_announcement: ""
                  payload: "{{ new_state_text }}"
                  indicator: ""

          - alias: "Toggle surround amplifier"
            conditions:
              - condition: template
                value_template: "{{ ir_hash == '0xc2997ec2' }}"
            sequence:
              - variables:
                  currently_on: "{{ is_state('switch.tv_surround_amp_power_in_loft_x27pp', 'on') }}"
              - variables:
                  new_state_text: "{{ 'Off' if currently_on else 'On' }}"

              - choose:
                  - conditions:
                      - condition: template
                        value_template: "{{ currently_on }}"
                    sequence:
                      - action: switch.turn_off
                        target:
                          entity_id: switch.tv_surround_amp_power_in_loft_x27pp
                default:
                  - action: switch.turn_on
                    target:
                      entity_id: switch.tv_surround_amp_power_in_loft_x27pp

              - action: script.view_road_announcement
                data:
                  channels: "sony_tv_lounge"
                  title: "View Road"
                  short_announcement: "Surround Amplifier"
                  long_announcement: ""
                  payload: "{{ new_state_text }}"
                  indicator: ""
