#!/usr/bin/env python3
import os
import pygame
from time import sleep
from datetime import datetime
from urllib import request
import json
import sys

try:
    req = request.Request('http://imp.lan:8123/api/states/input_boolean.on_air')
    req.add_header('Authorization', 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJhZDVkZDNiNzYwODY0YThjODNmYTg4ZDNhYjc0NGEzOSIsImlhdCI6MTY1NjU4ODIyNCwiZXhwIjoxOTcxOTQ4MjI0fQ.YfH2ntUkLCqx9Fkr9SUi9H7jxBta3mamdU918RlDGfY')
    r = request.urlopen(req)
    data = json.loads(r.read())
    if data["state"] == "on":
        print("Currently On Air, won't chime.")
        sys.exit(0)
except Exception as exc:
    print(exc)
    print("Failed to get On Air state, continuing...")
    pass

dirname = os.path.dirname(os.path.realpath(__file__))

pygame.mixer.init(frequency=44100, size=-16, buffer=1024, channels=1)
high = pygame.mixer.Sound(f"{dirname}/high.wav")
low = pygame.mixer.Sound(f"{dirname}/low.wav")
off = pygame.mixer.Sound(f"{dirname}/off.wav")

sleep(1)

now = datetime.now()

if now.weekday() in (5,) and 1 < now.hour < 23:
    off.play()
    print("brng")
else:
    hours = now.hour % 12
    hours = 12 if hours == 0 else hours
    
    closest_minutes = sorted([0, 15, 30, 45, 60], key=lambda p: abs(now.minute - p))[0]
    closest_minutes = 60 if closest_minutes == 0 else closest_minutes
    parts = [15, 30, 45, 60].index(closest_minutes) + 1
    
    for i in range(parts):
      high.play()
      print("ding")
      sleep(1)
    
    if parts == 4:
        sleep(2)
        
        for i in range(hours):
          low.play()
          print("bong")
          sleep(2)

sleep(5)
