# LiveVideoMetadataApi provides metadata related to video player.
# Note: Some key-value pairs can be null. If they are, the data attribute
# will be set to nil otherwise the value will be used.
class StreamMetadataApi
  class << self
    attr_reader :broadcaster_logo, :broadcaster_display_name, :broadcaster_title,
                :broadcaster_game, :channel_preview_url

    # Calls twitch api on the given channel.
    # Note: /streams api is only used when stream is actually live.
    # @param channel [String] Channel specified to video player
    # @return response [Json] Video Player metatdata
    def get_stream_metadata(channel)
      api_base_url = "https://api.twitch.tv/kraken/streams/"
      endpoint = (api_base_url + channel)
      response = HTTParty.get(endpoint,
                              headers: {'Accept' => 'application/vnd.twitchtv.v3+json',
                                        'Client-ID' => '7j65feoxl6nd7q7c5jt7uu61j60eqhp'})

      if response.code == 200
        @response = response
      else
        raise Exception.new("API request error.\n\tEndpoint: PUT #{endpoint}\n\tResponse Code: #{response.code}")
      end

      if @response['stream'].nil?
        raise "Error: #{VideoPlayerData.player_channel} is currently offline!"
      else
        set_broadcaster_logo
        set_broadcaster_display_name
        set_broadcaster_title
        set_broadcaster_game
        set_channel_preview_url
      end
    end

    private def set_broadcaster_logo
      @broadcaster_logo = @response['stream']['channel']['logo']
    end

    private def set_broadcaster_display_name
      @broadcaster_display_name = @response['stream']['channel']['display_name']
    end

    private def set_broadcaster_title
      @broadcaster_title = @response['stream']['channel']['status']
    end

    private def set_broadcaster_game
      @broadcaster_game = @response['stream']['channel']['game']
    end

    # Get the template url for channel preview image.
    # Example: template: "https://static-cdn.jtvnw.net/previews-ttv/live_user_monstercat-{width}x{height}.jpg"
    # Developers confirmed that the dimensions are hardcoded, so split at the templat '-{' and add in dimensions.
    private def set_channel_preview_url
      channel_preview_template = @response['stream']['preview']['template']
      split_preview_template = channel_preview_template.split('-{')
      @channel_preview_url = split_preview_template[0] + '-1280x720.jpg'
    end
  end
end
