require 'time'


module Youtube
  class VideoItem
    attr_reader :id, :title, :channel_id, :published_at, :thumbnail_url, :raw_tags

    def initialize item
      snippet = item.fetch('snippet')

      @id = item.fetch('id')
      @title = snippet['title']
      @channel_id = snippet['channelId']
      @published_at = Time.iso8601(snippet['publishedAt'])
      @thumbnail_url = pick_thumbnail(snippet['thumbnails'] || { })
      @raw_tags = snippet['tags'] || []
    end

    def url = "https://www.youtube.com/watch?v=#{ @id }"

    private

    def pick_thumbnail thumbnails
      ['maxres', 'standard', 'high', 'medium', 'default'].each do |key|
        url = thumbnails.dig(key, 'url')
        return url if url.present?
      end

      nil
    end
  end
end
