$(document).on "turbolinks:load", ->
  subscribeToBroadcast = (broadcastToken) -> App.cable.subscriptions.create { channel: "BroadcastsChannel", token: broadcastToken },
    connected: ->
      # Called when the subscription is ready for use on the server
      console.info "Subscribed to channel for broadcast:#{broadcastToken}"

    disconnected: ->
      # Called when the subscription has been terminated by the server

    received: (data) ->
      switch data.event
        when "broadcast_stream_update"
          return unless document.querySelector("meta[name=broadcast-token][current=true][content='#{broadcastToken}']")
          @refreshBroadcastVideo(data)
        when "stream_recording_ready"
          return unless document.querySelector("meta[name=broadcast-token][current=true][content='#{broadcastToken}']")
          @showBroadcastRecordings(data)
        when "file_upload_update"
          return unless document.querySelector("meta[name=broadcast-token][content='#{broadcastToken}']")
          @refreshBroadcastFilesTab(data)

    refreshBroadcastVideo: (data) ->
      $("#broadcast_updates").html data.status_content
      if data.streamer_status == 'recording' && data.status == 'active'
        $("#broadcast_video").html data.video_content
        new (Clappr.Player)(
          parentId: '#broadcast_video'
          source: data.playback_url
          width: '100%',
          height: '100%',
          mute: true,
          autoPlay: true,
          hlsMinimumDvrSize: 1)
      if data.streamer_status == "idle" && data.status == "idle"
        $("#broadcast_video").html data.video_content

    showBroadcastRecordings: (data) ->
      $(".flash-message").html data.flash_content
      $("#broadcast_recordings").html data.recordings_content
      $("#broadcast_recordings_nav").html data.recordings_nav_content

    refreshBroadcastFilesTab: (data) ->
      $("#broadcast_file_list_#{data.broadcast_token}").html data.files_content
      $("#broadcast_files_pagination_#{data.broadcast_token}").html data.pagination_content

  # Create a channel subscription for every broadcast included in the meta tags
  get_token = (meta) -> meta.getAttribute("content")
  broadcast_tokens = (get_token broadcast_meta for broadcast_meta in document.querySelectorAll("meta[name=broadcast-token]"))
  subscribeToBroadcast token for token in broadcast_tokens
