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

context.JK.SinglePlayerProfileGuardDialog = class SinglePlayerProfileGuardDialog
  constructor: (@app) ->
    @rest = context.JK.Rest()
    @client = context.jamClient
    @logger = context.JK.logger
    @gearUtils = context.JK.GearUtilsInstance
    @screen = null
    @dialogId = 'single-player-profile-dialog';
    @dialog = null;

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

    @dialog = $('[layout-id="' + @dialogId + '"]');
    @app.bindDialog(@dialogId, dialogBindings);
    @content = @dialog.find(".dialog-inner")
    @audioLatency = @dialog.find('.audio-latency')
    @btnPrivateSession = @dialog.find('.btn-private-session')
    @btnGearSetup = @dialog.find('.btn-gear-setup')
    @btnRescan = @dialog.find('.btn-rescan')
    @rescanningNotice = @dialog.find('.rescanning-notice')

    @btnPrivateSession.on('click', @onPrivateSessionChoice)
    @btnGearSetup.on('click', @onGearSetupChoice)
    @btnRescan.on('click', @onRescan)

  beforeShow:() =>
    @dialog.data('result', { choice: null})


  onRescan: () =>
    @gearUtils.scheduleAudioRestart('single-player-guard', 1000, @beforeScan, @afterScan)

  beforeScan: () =>
    @dialog.find('.action-buttons a').addClass('disabled')
    @rescanningNotice.show();

  afterScan: (canceled) =>
    @dialog.find('.action-buttons a').removeClass('disabled')
    @rescanningNotice.hide();

    if !canceled
      result = context.jamClient.ReloadAudioSystem(true, true, true);

    @refresh();

  refresh:() =>
    canPlayWithOthers = @gearUtils.canPlayWithOthers()

    if canPlayWithOthers.isNoInputProfile
      @content.removeClass('high-latency').addClass('has-no-inputs')
    else
      @content.removeClass('has-no-input').addClass('high-latency')

    latency = '?'
    if canPlayWithOthers.audioLatency?
      latency = canPlayWithOthers.audioLatency.toFixed(2)

    @audioLatency.text("#{latency} milliseconds.")

  afterShow:() =>
    @refresh()



  onPrivateSessionChoice: () =>
    @dialog.data('result', { choice: 'private_session'})
    @app.layout.closeDialog(@dialogId)
    return false

  onGearSetupChoice: () =>
    @dialog.data('result', { choice: 'gear_setup'})
    @app.layout.closeDialog(@dialogId)
    return false