module SpiritsHelper
  require 'lunartic'
  require 'net/http'
  require 'json'

  MOON_AGES_FOR_WORKINGS = [2, 4, 6, 8, 10, 12, 14].freeze
  CHALDEAN_ORDER = %w[Saturn Jupiter Mars Sun Venus Mercury Moon].freeze
  API_ENDPOINT = "http://www.planetaryhoursapi.com/api/"

  def hours_for_planet_on_weekday(datetime)
    desired_planet = planet_for_day(datetime.strftime("%A"))
    
    longitude = session[:longitude] ? session[:longitude].to_f : -0.001545
    latitude = session[:latitude] ? session[:latitude].to_f : 51.477928
  
    data = fetch_planetary_data(datetime, latitude, longitude)
    
    solar_hours = data["Response"]["SolarHours"]
    lunar_hours = data["Response"]["LunarHours"]
    
    all_hours = solar_hours.merge(lunar_hours)
  
    planetary_hours_for_desired_planet = all_hours.values.select { |hour| hour["Ruler"] == desired_planet }
 
    planetary_hours_for_desired_planet.map do |hour|
      {
        start_time: DateTime.parse(hour["Start"]),
        end_time: DateTime.parse(hour["End"])
      }
    end
  end
   
  def fetch_planetary_data(datetime, latitude, longitude)
    date = datetime.strftime('%Y-%m-%d')
    uri = URI("#{API_ENDPOINT}#{date}/#{latitude},#{longitude}")
    response = Net::HTTP.get(uri)
    JSON.parse(response)
  end
  
def lunar_date(date)
  moon = Lunartic.on_date(date)
  age = moon.day.floor

  message = if MOON_AGES_FOR_WORKINGS.include?(age)
              "✅"
            else
              "⛔️"
            end

  "#{moon_phase_emoji(date)} #{age} days #{message}"
end

def moon_phase_emoji(date)
  moon = Lunartic.on_date(date)
  phase = moon.phase
  
  case phase
  when :new
    '🌑' # New Moon
  when :waxing_crescent
    '🌒' # Waxing Crescent Moon
  when :first_quarter
    '🌓' # First Quarter Moon
  when :waxing_gibbous
    '🌔' # Waxing Gibbous Moon
  when :full
    '🌕' # Full Moon
  when :waning_gibbous
    '🌖' # Waning Gibbous Moon
  when :last_quarter
    '🌗' # Last Quarter Moon
  when :waning_crescent
    '🌘' # Waning Crescent Moon
  else
    '❓' # Unknown phase
  end
end

def celestial_emoji(body_name)
  case body_name.downcase
  when 'mercury'
    '☿' # Symbol for Mercury
  when 'venus'
    '♀' # Symbol for Venus
  when 'mars'
    '♂' # Symbol for Mars
  when 'jupiter'
    '♃' # Symbol for Jupiter
  when 'saturn'
    '♄' # Symbol for Saturn
  when 'sun'
    '☀' # Symbol for Sun
  when 'moon'
    '🌕' # Symbol for Full Moon (as a general representation of the Moon)
  else
    '❓' # Unknown celestial body
  end
end

def time_matches_rank?(datetime, rank_name)
  latitude = session[:latitude].to_f
  
  sunrise_time = session[:sunrise] ? DateTime.parse(session[:sunrise]) : datetime.change(hour: 5)
  sunset_time = session[:sunset] ? DateTime.parse(session[:sunset]) : datetime.change(hour: 20)

  # Adjust twilight duration based on latitude. This is a rough approximation.
  twilight_adjustment = [30 + (latitude.abs / 90) * 30, 60].min.minutes

  dawn_time = sunrise_time - twilight_adjustment if sunrise_time
  twilight_end_time = sunset_time + twilight_adjustment if sunset_time

  rank = Rank.find_by(type_name: rank_name)

  case rank_name
  when 'King'
    datetime.hour.between?(9, 12) || datetime.hour.between?(15, sunset_time.hour)
  when 'Marquis'
    datetime.hour.between?(15, 21) || datetime.hour.between?(21, sunrise_time.hour)
  when 'Duke'
    datetime.between?(sunrise_time, datetime.change(hour: 12))
  when 'Knight'
    datetime.between?(dawn_time, sunrise_time) || datetime.hour.between?(16, sunset_time.hour)
  when 'President'
    return false if datetime.between?(sunset_time, twilight_end_time)
    true
  when 'Earls'
    true  # The conditions for this rank need further context as it mentions "places whither men resort not, or where no noise is", which can't be checked using just the date and time.
  else
    false
  end
end  

  def planet_for_day(weekday)
    case weekday
    when 'Sunday'
      'Sun'
    when 'Monday'
      'Moon'
    when 'Tuesday'
      'Mars'
    when 'Wednesday'
      'Mercury'
    when 'Thursday'
      'Jupiter'
    when 'Friday'
      'Venus'
    when 'Saturday'
      'Saturn'
    end
  end
end