class MuxLiveStream
  def id
    live_stream.data.id
  end

  def key
    live_stream.data.stream_key
  end

  def playback_id
    playback.data.id
  end

  def destroy_stream(stream_uid)
    client.delete_live_stream(stream_uid)
  end

  private

  def live_stream
    @live_stream ||= create_live_stream
  end

  def playback
    @playback ||= create_playback
  end

  # Source: https://github.com/muxinc/mux-ruby/blob/1.4.0/examples/video/exercise-live-streams.rb

  def create_live_stream
    create_asset_request = MuxRuby::CreateAssetRequest.new
    create_asset_request.playback_policy = [MuxRuby::PlaybackPolicy::PUBLIC]
    create_asset_request.mp4_support = "standard"
    create_live_stream_request = MuxRuby::CreateLiveStreamRequest.new
    create_live_stream_request.new_asset_settings = create_asset_request
    create_live_stream_request.playback_policy = [MuxRuby::PlaybackPolicy::PUBLIC]
    create_live_stream_request.reduced_latency = reduced_latency_enabled?
    create_live_stream_request.test = test_mode_enabled?

    client.create_live_stream(create_live_stream_request)
  end

  def create_playback
    create_playback_id_request = MuxRuby::CreatePlaybackIDRequest.new
    # TODO: Use signed policy in the future
    # create_playback_id_request.policy = MuxRuby::PlaybackPolicy::SIGNED
    create_playback_id_request.policy = MuxRuby::PlaybackPolicy::PUBLIC

    client.create_live_stream_playback_id(live_stream.data.id, create_playback_id_request)
  end

  def reduced_latency_enabled?
    ENV["MUX_REDUCED_LATENCY_ENABLED"].present?
  end

  def test_mode_enabled?
    !ENV["MUX_TEST_MODE_DISABLED"].present?
  end

  def client
    @client ||= MuxRuby::LiveStreamsApi.new
  end
end
