$ = jQuery
context = window
context.JK ||= {}

context.JK.SoundCloudPlayerDialog = class SoundCloudPlayerDialog
  constructor: (@app) ->
    @rest = context.JK.Rest()
    @client = context.jamClient
    @logger = context.JK.logger
    @screen = null
    @dialogId = 'sound-cloud-player-dialog'
    @dialog = null    
    @player = null

  initialize:(@url, @caption) =>
    dialogBindings = {
      'beforeShow' : @beforeShow,
      'afterShow' : @afterShow,
      'afterHide' : @afterHide
    }

    @dialog = $('[layout-id="' + @dialogId + '"]')
    @app.bindDialog(@dialogId, dialogBindings) 
    @player = @dialog.find(".sound-cloud-player")  
    @dialog.find(".caption").text("'#{@caption}'")
    @player.addClass("hidden")

  beforeShow:() =>
    @player.addClass("hidden")
    @player.attr("src", "")    

    # the Windows client does not play back correctly
    if context.jamClient.IsNativeClient()
      context.JK.popExternalLink(@url)
      return false
    else
      u = encodeURIComponent(@url)
      src = "https://w.soundcloud.com/player/?url=#{u}&auto_play=true&hide_related=false&show_comments=true&show_user=true&show_reposts=false&visual=true&loop=true"
      @player.attr("src", src)

  afterShow:() =>
    @player.removeClass("hidden")

  showDialog:() =>
    @app.layout.showDialog(@dialogId)

  afterHide: () =>
    @player.attr('src', '')

  