###############################################################################
#   @author         :   Mahasri Kalavala
#   @date           :   09/20/2018
#   @package        :   scripts
#   @description    :   All my scripts are here in one place!
################################################################################
#    _____           _       _
#   / ____|         (_)     | |
#  | (___   ___ _ __ _ _ __ | |_ ___
#   \___ \ / __| '__| | '_ \| __/ __|
#   ____) | (__| |  | | |_) | |_\__ \
#  |_____/ \___|_|  |_| .__/ \__|___/
#                     | |
#                     |_|
################################################################################

homeassistant:
  customize:
    script.all_indoor_lights_off:
      friendly_name: All Indoor Lights & Switches OFF
    script.home_status:
      friendly_name: Home Status (Hourly Report)
    script.home_mode_away:
      friendly_name: Set Home Mode to AWAY
    script.good_night_tts:
      friendly_name: Good Night TTS Report

script:
  toggle_do_not_disturb:
    sequence:
      - service: input_boolean.toggle
        entity_id: input_boolean.do_not_disturb

  play_ringtone:
    sequence:
      - service: xiaomi_aqara.play_ringtone
        data:
          gw_mac: !secret xiaomi_mac
          ringtone_id: 10
          ringtone_vol: 30

  play_fav_song:
    sequence:
      - service: media_player.volume_set
        entity_id: media_player.living_room, media_player.upstairs
        data:
          volume_level: "0.15"
      - service: media_player.play_media
        data:
          entity_id: media_player.living_room, media_player.upstairs
          media_content_id: !secret fav_song_url
          media_content_type: "music"

  play_dog_sounds:
    sequence:
      - service: media_player.volume_set
        entity_id: media_player.living_room, media_player.upstairs
        data:
          volume_level: "1.0"
      - service: media_player.play_media
        data:
          entity_id: media_player.living_room, media_player.upstairs
          media_content_id: !secret dog_sound_url
          media_content_type: "music"
      - delay: "00:00:05"
      - service: media_player.play_media
        data:
          entity_id: media_player.living_room, media_player.upstairs
          media_content_id: !secret dog_sound_url
          media_content_type: "music"
      - delay: "00:00:05"
      - service: media_player.play_media
        data:
          entity_id: media_player.living_room, media_player.upstairs
          media_content_id: !secret dog_sound_url
          media_content_type: "music"

  home_mode_away:
    sequence:
      - service: script.all_indoor_lights_off
      - service: input_boolean.turn_on
        entity_id: input_boolean.notify_camera_alerts
      - service: alarm_control_panel.alarm_arm_away
        data:
          entity_id: alarm_control_panel.home
      - service: script.notify_me
        data:
          message: >
            No one is at home. Cameras rolling, Indoor lights are OFF. Your home security system is turned ON!

  ###############################################################################
  # The following script runs when no one is home. It excludes some lights
  # and switches like front porch and backyard lights...etc for safety reasons.
  ###############################################################################
  all_indoor_lights_off:
    sequence:
      - service: light.turn_off
        data_template:
          entity_id:
            - light.family_room_lights
            - light.hue_color_lamp_1
            - light.hue_color_lamp_2
            - light.hue_color_lamp_3
            - light.master_bedroom_1
            - light.master_bedroom_2
            - light.master_bedroom_lights

      - service: switch.turn_off
        data_template:
          entity_id:
            - switch.basement_left
            - switch.basement_right
            - switch.front_room
            - switch.garage
            - switch.garage_shop_lights
            - switch.srinika_bedroom
            - switch.hasika_bed_accent
            - switch.hasika_bedroom
            - switch.kitchen_switch
            - switch.office_room
            - switch.guest_room
            - switch.officeroom_accent_lights
            - switch.chromecast_monitor
            - switch.master_bathroom_lights

  xiaomi_red:
    sequence:
      - service: light.turn_on
        data:
          entity_id: light.gateway_light_34ce008ad65d
          brightness: 255
          rgb_color: [255, 0, 0]

  xiaomi_blue:
    sequence:
      - service: light.turn_on
        data:
          entity_id: light.gateway_light_34ce008ad65d
          brightness: 255
          rgb_color: [0, 0, 255]

  xiaomi_green:
    sequence:
      - service: light.turn_on
        data:
          entity_id: light.gateway_light_34ce008ad65d
          brightness: 255
          rgb_color: [0, 255, 0]

  ###############################################################################
  # A script that toggles Nest Thermostat between eco/away & non-eco/away modes
  ###############################################################################
  toggle_climate:
    sequence:
      - service: climate.set_away_mode
        data_template:
          entity_id: climate.dining_room
          away_mode: "{{ false if state_attr('climate.dining_room', 'away_mode') == 'on' else true }}"

  ###############################################################################
  #   _   _       _   _  __
  #  | \ | |     | | (_)/ _|
  #  |  \| | ___ | |_ _| |_ _   _
  #  | . ` |/ _ \| __| |  _| | | |
  #  | |\  | (_) | |_| | | | |_| |
  #  |_| \_|\___/ \__|_|_|  \__, |
  #                          __/ |
  #                         |___/
  # Notify Related Scripts
  ###############################################################################
  notify_me_with_picture:
    sequence:
      - condition: state
        entity_id: input_boolean.text_alerts
        state: "on"
      - condition: template
        value_template: '{{- message | trim != "" -}}'
      - service: telegram_bot.send_message
        data:
          title: "{{- title -}}"
          message: "{{- message -}}"
          data:
            photo:
              - file: "{{- file -}}"
                caption: "{{- caption -}}"

  notify_me:
    sequence:
      - condition: state
        entity_id: input_boolean.text_alerts
        state: "on"
      - condition: template
        value_template: '{{ message | trim != "" }}'
      - service: telegram_bot.send_message
        data:
          message: "{{ message }}"
      - service: notify.android_tv_fire_tv
        data:
          message: "{{ message }}"
          title: Mahasri Bot
          data:
            color: red
            duration: 10
            transparency: 1%
            icon: 
              path: /config/www/{{- [ "suresh.jpg", "srinika.jpg", "mallika.jpg", "hasika.jpg" ] | random  -}}

  good_night_tts:
    sequence:
      - service: script.voice_notify
        data_template:
          message: !include ../templates/goodnight.yaml

  ###############################################################################
  # Voice Notify
  # Conditions:
  #   => Only Announce when people are home. Except in emergency mode!
  #   => Only Announce when Music is NOT being played
  ###############################################################################
  voice_notify:
    sequence:
      - condition: template
        value_template: "{{ states('input_boolean.voice_notifications') == 'on' }}"
      - condition: template
        value_template: "{{ states('input_boolean.do_not_disturb') | lower == 'off' }}"
      - condition: template
        value_template: "{{ message | trim != '' }}"
      - condition: template
        value_template: "{{ states('input_boolean.home_mode_away') == 'off' }}"
      - condition: template
        value_template: >
          {% if only_at_night | default('no', true ) == "yes" %}
            {% if states('sun.sun') == "above_horizon" %}
              false
            {% else %}
              true
            {% endif %}
          {% else %}
            true
          {% endif %}
      - service: media_player.volume_set
        entity_id: media_player.living_room, media_player.upstairs
        data_template:
          volume_level: >
            {% if states('input_boolean.emergency_mode') == "on" %}
              {{ states('input_number.tts_volume_level_alert') }}
            {% else %}
              {% if now().hour | int < 12 and now().hour | int > 6 %}
                {{ states('input_number.tts_volume_level_morning') }}
              {% elif now().hour|int > 12 and now().hour|int < 20 %}
                {{ states('input_number.tts_volume_level_afternoon') }}
              {% else %}
                {{ states('input_number.tts_volume_level_evening') }}
              {% endif %}
            {% endif %}
      - service: tts.amazon_polly_say
        entity_id: media_player.living_room, media_player.upstairs
        data_template:
          cache: true
          message: >
            {% set msg = "" %}
            {% macro getGreeting() %}
              {% if greeting | default('yes', true ) == "yes" %}
                {% if now().hour|int < 12 %}
                  Good morning.
                {% elif now().hour|int < 18 %}
                  Good afternoon.
                {% else %}
                  Good evening.
                {% endif %}
              {% endif %}
            {% endmacro %}
            {%- macro getEndGreeting() -%}
              {%- if greeting |default('yes', true ) == "yes" -%}
                Thank you!
              {%- endif -%}
            {%- endmacro -%}
            {% set msg = msg + "<speak> " %}
            {% set msg = msg + getGreeting() %}
            {% set msg = msg + ". " + message %}
            {% set msg = msg.replace(".", " <break time='0.5s'/> ") %}
            {% set msg = msg + " " + getEndGreeting() %}
            {% set msg = msg + " </speak>" %}
            {{ msg }}

  ###############################################################################
  # Greeting
  ###############################################################################
  voice_greeting:
    sequence:
      - service: tts.amazon_polly_say
        entity_id: media_player.living_room, media_player.upstairs
        data_template:
          cache: true
          message: >
            {% set msg = "" %}
            {% macro getGreeting() %}
              {% if greeting | default('yes', true ) == "yes" %}
                {% if now().hour|int < 12 %}
                  Good morning.
                {% elif now().hour|int < 18 %}
                  Good afternoon.
                {% else %}
                  Good evening.
                {% endif %}
              {% endif %}
            {% endmacro %}
            {% set msg = msg + "<speak> " %}
            {% set msg = msg + " " + getGreeting() %}
            {% set msg = msg.replace(".", " <break time='0.5s'/> ") %}
            {% set msg = msg + " </speak>" %}
            {{ msg }}

  ###############################################################################
  # Status around the house
  ###############################################################################
  home_status:
    sequence:
      - service: script.voice_notify
        data_template:
          message: !include ../templates/home_status.yaml

  ###############################################################################
  # Display message on LED Matrix Screen
  ###############################################################################
  led_message:
    sequence:
      - condition: state
        entity_id: input_boolean.led_alerts
        state: "on"
      - service: mqtt.publish
        data_template:
          topic: messageboard/messages
          payload: "{{ message }}"

  ###############################################################################
  # Notifies to take pills, starts timer again!
  # Voice notifications at home - only if the option is selected.
  ###############################################################################
  remind_pill:
    sequence:
      - service: script.notify_me
        data:
          message: "ALERT: PLEASE TAKE YOUR TABLETS!"
      - service: timer.start
        entity_id: timer.timer_pill_reminder
      - condition: template
        value_template: "{{ states('input_boolean.pill_voice_notification') == 'on' }}"
      - service: script.voice_notify
        data_template:
          message: >
            Please take the tablets. It looks like you have forgotten to take today's 
            dose of tablets... Once again, this is a reminder for you to take the tablets.

  ###############################################################################
  # Stops timer, Records that the pills are taken, and notifies!
  ###############################################################################
  pill_taken:
    sequence:
      - service: timer.cancel
        entity_id: timer.timer_pill_reminder
      - service: input_boolean.turn_on
        entity_id: input_boolean.pill_taken
      - service: script.notify_me
        data_template:
          message: >
            Thank you for taking tablets.
            {%- if state_attr('sensor.allergy_index_today', 'rating') != None %}
              {{- " Today's pollen level is : " ~ state_attr('sensor.allergy_index_today', 'rating') }}.
            {%- endif -%}
      - condition: template
        value_template: "{{ states('input_boolean.pill_voice_notification') == 'on' }}"
      - service: script.voice_notify
        data:
          message: "Thank you for taking tablets on time!"
