about summary refs log tree commit diff
path: root/app/controllers/api/v1/werewolf_controller.rb
blob: 3e240adf5d454e2bad3f54115fd96d687a4c5700 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# frozen_string_literal: true

class Api::V1::WerewolfController < Api::BaseController
  respond_to :json
  skip_before_action :set_cache_headers
  skip_before_action :require_authenticated_user!

  def index
    render json: werewolf_info
  end

  private

  def werewolf_info
    Rails.cache.fetch("werewolf:info", expires_in: 6.hours) do
      this_fraction = moon_fraction(Time.now.utc)
      {
        werewolf: this_fraction > 0.99,
        lastwolf: last_full_moon.strftime('%F'),
        nextwolf: next_full_moon.strftime('%F'),
        fullness: "#{(this_fraction * 100).round}%",
      }
    end
  end

  def last_full_moon
    now     = Time.now.utc.beginning_of_day
    offset  = 0
    growing = false
    moon    = moon_fraction(now)
    last    = 0

    until growing && moon < last
      last = moon
      offset += 1
      moon = moon_fraction(now - offset.hours)
      growing = true unless growing || moon < last
    end

    offset -= 1
    now - offset.hours
  end

  def next_full_moon
    now     = Time.now.utc.beginning_of_day
    offset  = 0
    growing = false
    moon    = moon_fraction(now)
    last    = 0

    until growing && moon < last
      last = moon
      offset += 1
      moon = moon_fraction(now + offset.hours)
      growing = true unless growing || moon < last
    end

    offset -= 1
    now + offset.hours
  end

  def moon_fraction(time)
    SunCalc.moon_illumination(time)[:fraction]
  end
end