class StreamNotificationsController < ApplicationController
  skip_before_action :require_login
  skip_after_action :verify_authorized, except: :index
  skip_after_action :verify_policy_scoped, only: :index
  skip_before_action :verify_authenticity_token

  before_action :set_broadcast, only: :create

  def create
    case notification_type
    when "video.live_stream.connected"
      @broadcast.streamer_connected!
      notify_users
    when "video.live_stream.recording"
      @broadcast.streamer_recording!
      notify_users
    when "video.live_stream.active"
      @broadcast.active!
      notify_users
    when "video.live_stream.disconnected"
      @broadcast.streamer_disconnected!
      notify_users
    when "video.live_stream.idle"
      @broadcast.streamer_idle!
      @broadcast.idle!
      notify_users
    when "video.asset.static_renditions.ready"
      asset_uid = notification.dig(:object, :id)
      playback_uid = notification.dig(:data, :playback_ids, 0, :id)
      file_name = notification.dig(:data, :static_renditions, :files, -1, :name)

      recording = @broadcast.broadcast_recordings.create!(asset_uid: asset_uid, asset_playback_uid: playback_uid, file_name: file_name)
      recordings = @broadcast.broadcast_recordings.order_by_recent.paginate(page: params[:page])

      link = helpers.link_to(recording.broadcast_name.titleize, recording.download_url, target: "_blank")
      message = "Your recent live stream has been recorded and is available for download here: #{link}"
      BroadcastsChannel.stream_recording_ready(@broadcast, recordings, message)
    else
      Rails.logger.info notification_type
      Rails.logger.info notification
    end

    head :ok
  end

  private

  def notification
    params
  end

  def notification_type
    notification.dig(:type)
  end

  def notification_object_id
    notification.dig(:object, :id)
  end

  def set_broadcast
    if notification_type == "video.asset.static_renditions.ready"
      live_stream_id = notification.dig(:stream_notification, :data, :live_stream_id)
      @broadcast = Broadcast.find_by!(stream_uid: live_stream_id)
    else
      @broadcast = Broadcast.find_by!(stream_uid: notification_object_id)
    end
  end

  def notify_users
    BroadcastsChannel.broadcast_stream_updates(@broadcast)
  end
end
