# https://www.home-assistant.io/integrations/sonos
sonos:
  media_player:
    hosts: !secret sonos_hosts

# https://www.home-assistant.io/integrations/spotify
spotify:
  client_id: !secret spotify_client_id
  client_secret: !secret spotify_client_secret

group:
  all_sonos:
    name: All Sonos
    entities:
      - media_player.master_bedroom
      - media_player.living_room
      - media_player.kitchen
      - media_player.bathroom

input_select:
  sonos_leader:
    name: Sonos Leader
    icon: mdi:speaker
    options:
      - media_player.master_bedroom
      - media_player.living_room
      - media_player.kitchen

binary_sensor:
  - platform: template
    sensors:
      sonos_leader_paused:
        value_template: "{{ is_state(states.input_select.sonos_leader.state, 'paused') }}"
        entity_id:
          - input_select.sonos_leader
          - media_player.master_bedroom
          - media_player.kitchen
          - media_player.living_room

script:
  music_play:
    alias: Music · Play
    sequence:
      - service: script.music_join_sonoses
      - service: media_player.volume_set
        entity_id: group.all_sonos
        data_template:
          volume_level: "{{ volume | default(0.3) }}"
      - service: media_player.shuffle_set
        data_template:
          entity_id: "{{ states('input_select.sonos_leader') }}"
          shuffle: "{{ shuffle | default(true) }}"
      - service: media_player.select_source
        data_template:
          entity_id: "{{ states('input_select.sonos_leader') }}"
          source: "{{ playlist | default('Evening Chill') }}"

  music_join_sonoses:
    alias: Music · Join Sonoses
    sequence:
      - service: sonos.join
        entity_id: group.all_sonos
        data_template:
          master: "{{ states('input_select.sonos_leader') }}"

automation:
  - alias: Music · Play/Pause on Magic Cube Knock
    trigger:
      platform: event
      event_type: zha_event
      event_data:
        device_ieee: !secret magic_cube_ieee
        command: knock
    action:
      - service: media_player.media_play_pause
        data_template:
          entity_id: "{{ states('input_select.sonos_leader') }}"

  - alias: Music · Volume down on Magic Cube rotate left
    trigger:
      platform: event
      event_type: zha_event
      event_data:
        device_ieee: !secret magic_cube_ieee
        command: rotate_left
    action:
      - service: media_player.volume_down
        data_template:
          entity_id: "{{ states('input_select.sonos_leader') }}"

  - alias: Music · Volume up on Magic Cube rotate right
    trigger:
      platform: event
      event_type: zha_event
      event_data:
        device_ieee: !secret magic_cube_ieee
        command: rotate_right
    action:
      - service: media_player.volume_up
        data_template:
          entity_id: "{{ states('input_select.sonos_leader') }}"
