class BroadcastsChannel < ApplicationCable::Channel
  def subscribed
    broadcast = Broadcast.find_by_token!(params[:token])
    stream_for broadcast
  end

  def unsubscribed
    # Any cleanup needed when channel is unsubscribed
  end

  def self.broadcast_stream_updates(broadcast)
    status_content = ApplicationController.render partial: "broadcasts/broadcast_status", locals: { broadcast: broadcast }
    video_content = ApplicationController.render partial: "broadcasts/video", locals: { broadcast: broadcast }

    broadcast_to broadcast, {
      event: :broadcast_stream_update,
      status: broadcast.status,
      playback_url: broadcast.stream_playback_url,
      video_content: video_content,
      status_content: status_content,
      streamer_status: broadcast.streamer_status
    }
  end

  def self.stream_recording_ready(broadcast, recordings, message)
    flash_message = OpenStruct.new(notice: message, alert: nil)
    flash_content = ApplicationController.render partial: "application/flash", locals: { flash: flash_message }
    recordings_content = ApplicationController.render partial: "broadcasts/broadcast_recordings", locals: { recordings: recordings, broadcast: broadcast }
    recordings_nav_content = ApplicationController.render partial: "broadcasts/broadcast_recording_nav", collection: recordings, as: :broadcast_recording

    broadcast_to broadcast,
      event: :stream_recording_ready,
      flash_content: flash_content,
      recordings_content: recordings_content,
      recordings_nav_content: recordings_nav_content
  end

  def self.broadcast_file_upload_updates(broadcast, files, pagination_content)
    files_content = ApplicationController.render partial: "broadcasts/file", collection: files

    broadcast_to broadcast, {
      event: :file_upload_update,
      broadcast_token: broadcast.token,
      files_content: files_content,
      pagination_content: pagination_content
    }
  end
end
