class ProjectsChannel < ApplicationCable::Channel

  def subscribed
    # TODO: How can we get the current account in this context
    project = current_user.accessible_projects_for(current_user.primary_account).find(params[:id])
    stream_for project
  end

  def unsubscribed
    # Any cleanup needed when channel is unsubscribed
  end

  def self.broadcast_video_analysis_update(video)
    content = ApplicationController.render partial: "video_analyses/video_status_updated", locals: { video: video }
    broadcast_to video.project, event: :video_status_update, content: content
  end

  def self.broadcast_download_generation_update(download, notification)
    if download.failure?
      flash = OpenStruct.new(notice: nil, alert: notification)
    else
      flash = OpenStruct.new(notice: notification, alert: nil)
    end

    content = ApplicationController.render partial: "application/flash", locals: { flash: flash }
    broadcast_to download.project, event: :download_status_update, content: content
  end

  def self.conference_recording_ready(project, recording)
    link = ApplicationController.helpers.link_to('Download here.', recording.service_url, target: '_blank', class: 'alert-link')
    notification = "A recording of your video conference is now available. #{link}"
    flash = OpenStruct.new(notice: notification)
    content = ApplicationController.render partial: 'application/flash', locals: { flash: flash }
    broadcast_to project, event: :conference_recording_ready, content: content
  end
end
