#!/usr/bin/env ruby

require 'huemote'

LIGHT_NAMES = ['Office 1', 'Office 2']
TEMPS = {
  'bright' => {
    brightness: 254,
    temp: 4200,
  },
  'cloudy' => {
    brightness: 220,
    temp: 3500,
  },
  'sunrise' => {
    brightness: 180,
    temp: 2200,
  },
  'morning' => {
    brightness: 220,
    temp: 2600,
  },
  'noon' => {
    brightness: 254,
    temp: 4200,
  },
  'sunset' => {
    brightness: 210,
    temp: 2600,
  },
  'night' => {
    brightness: 160,
    temp: 2300,
  },
  'midnight' => {
    brightness: 120,
    temp: 2100,
  },
}
TEMPS['sunny'] = TEMPS['bright']
TEMPS['overcast'] = TEMPS['cloudy']

setting = ARGV[0]
brightness = ARGV[1] || 220
transition = ARGV[2]
Huemote.set_ip '192.168.0.2'
lights = LIGHT_NAMES.map { |name| Huemote::Light.find(name) }

def kelvin_to_mireds(temp)
  [[1_000_000 / temp, 154].max, 500].min
end

case setting
when 'off'
  lights.each(&:off!)
when 'on'
  lights.each(&:on!)
else
  lights.each(&:on!)
  attrs = TEMPS[setting] || {
    temp: setting.to_i,
    brightness: brightness.to_i,
  }
  if attrs
    attrs[:bri] = attrs.delete(:brightness)
    if attrs[:temp]
      attrs[:ct] = kelvin_to_mireds(attrs.delete(:temp))
    end
    if transition
      # tenths of a second
      attrs[:transitiontime] = transition.to_i
    end
    lights.each do |l|
      l.send(:set!, attrs)
    end
  else
    puts "Unknown setting: #{setting}"
  end
end
