class Accuweather::WeatherService < ApplicationService
  def initialize(location_id)
    @location_id = location_id
    @api_key = Rails.application.secrets.accuweather_key
    @path = "http://dataservice.accuweather.com/currentconditions/v1/#{location_id}"
  end

  def call
    current_weather = $redis.get(@location_id)
    if current_weather.blank? || need_refresh(JSON.parse(current_weather))
      refresh_data
    else
      JSON.parse(current_weather)
    end
  end

  private
    def need_refresh(weather)
      weather_time = Time.at(weather['EpochTime']).utc.to_datetime
      weather_time < Time.zone.now - 15.minutes
    end

    def refresh_data
      resp = RestClient.get(@path, params: { details: true, apikey: @api_key })
      current_weather = JSON.parse(resp.body).first
      $redis.set(@location_id, JSON.dump(current_weather))
      current_weather
    rescue
      current_weather = $redis.get(@location_id)
      JSON.parse(current_weather) if current_weather.present?
    end
end
