module UserRewards
  module HypeTrainHelper
    def completed_level(hype_train)
      return 0 if hype_train.nil?

      if hype_train.level_progress.progression >= hype_train.level_progress.goal
        hype_train.level_progress.setting.level
      else
        hype_train.level_progress.setting.level - 1
      end
    end

    def current_level(hype_train)
      hype_train.level_progress.setting.level
    end

    def level_progress_percentage(level_progress)
      number_to_percentage(level_progress.progression.to_f / level_progress.goal * 100, precision: 0)
    end

    def all_eligible_rewards_by_level(hype_train, user_owned_rewards)
      level_settings = hype_train.config.difficulty_settings.select do |setting|
        setting.difficulty == hype_train.config.difficulty
      end.first.level_settings

      completed_levels = level_settings.select do |level|
        level.level <= completed_level(hype_train)
      end

      rewards_by_level = completed_levels.sort_by(&:level).map(&:rewards)
      owned_ids = user_owned_rewards.map(&:id)
      rewards_by_level.each do |rewards|
        rewards.each do |reward|
          if owned_ids.include?(reward.id)
            reward.owned = true
          end
        end
      end
    end

    def badge_image_url(badge)
      if badge == "current_conductor"
        "https://static-cdn.jtvnw.net/badges/v1/fae4086c-3190-44d4-83c8-8ef0cbe1a515/3"
      else
        "https://static-cdn.jtvnw.net/badges/v1/9c8d038a-3a29-45ea-96d4-5031fb1a7a81/3"
      end
    end

    def emote_image_url(emote_id)
      "https://static-cdn.jtvnw.net/emoticons/v1/#{emote_id}/5.0"
    end

    def filter_rewards_by_type(rewards, type)
      rewards.select { |reward| reward.type == type }
    end
  end
end
