module Preview
  class KnownSiteExtractor
    def self.thumbnail_url(uri)
      youtube_thumbnail(uri)
    end

    def self.youtube_video_id(uri)
      case uri.host&.downcase
      when 'youtu.be'
        uri.path.split('/').reject(&:blank?).first
      when 'www.youtube.com', 'youtube.com', 'm.youtube.com'
        uri.path == '/watch' ? URI.decode_www_form(uri.query.to_s).to_h['v'] : nil
      end&.then { _1 if _1.match?(/\A[A-Za-z0-9_-]{6,20}\z/) }
    end

    def self.niconico_video_id(uri)
      case uri.host&.downcase
      when 'www.nicovideo.jp', 'nicovideo.jp'
        uri.path[%r{\A/watch/(sm\d+)\z}, 1]
      when 'nico.ms'
        uri.path[%r{\A/(sm\d+)\z}, 1]
      end
    end

    def self.youtube_thumbnail(uri)
      id = youtube_video_id(uri)
      return unless id

      "https://i.ytimg.com/vi/#{ id }/hqdefault.jpg"
    end

    private_class_method :youtube_thumbnail
  end
end
