class Public::BroadcastsController < Public::BaseController
  skip_after_action :verify_authorized
  before_action :set_broadcast, only: [:show, :update]

  def show
    @conference_url = broadcast_zoom_meeting_url(@broadcast.token)
    @multi_view_broadcasts = multi_view_broadcasts
    @recordings = @broadcast.broadcast_recordings.order_by_recent.paginate(page: params[:page])
    @files = @broadcast.files.order("created_at DESC").paginate(page: params[:files_page])

    render 'broadcasts/show'
  end

  def update
    @broadcast.update(broadcast_params)
    @files = @broadcast.files.order("created_at DESC").paginate(page: 1)

    pagination_content = ApplicationController.render html: helpers.will_paginate(@files,params: { active_tab: params[:active_tab], page: params[:page], active_files_tab: params[:active_files_tab] })
    BroadcastsChannel.broadcast_file_upload_updates(@broadcast, @files, pagination_content)
  end

  private

  def broadcast_params
    params.require(:broadcast).permit(files: [])
  end

  def multi_view_broadcasts
    Broadcast.
      where(token: params[:multi_view_tokens]).
      order_by_recent.
      map do |b|
        files_page = params[:files_page] if params[:active_files_tab] == b.token
        MultiViewBroadcast.new(b, params[:multi_view_tokens], files_page)
      end
  end

  def set_broadcast
    @broadcast = Broadcast.find_by_token(params[:token])
  end

  class MultiViewBroadcast
    include Rails.application.routes.url_helpers

    delegate_missing_to :@broadcast

    def initialize(broadcast, multi_view_tokens, paginate_page)
      @broadcast = broadcast
      @multi_view_tokens = multi_view_tokens
      @paginate_page = paginate_page
    end

    def url
      broadcast_url(uid, multi_view_tokens: @multi_view_tokens, host: AppHost.new.domain_with_port, locale: I18n.locale)
    end

    def files
      @broadcast.files.order("created_at DESC").paginate(page: @paginate_page)
    end

    def uid
      token
    end

    def self.model_name
      Broadcast.model_name
    end
  end
end
