(function (context, $) {

  "use strict";

  context.JK = context.JK || {};

  // this dialog is shown when the user has a profile, but it's messed up.  This lets them try to fix it
  context.JK.AudioProfileInvalidDialog = function (app) {
    var ALERT_NAMES = context.JK.ALERT_NAMES;
    var EVENTS = context.JK.EVENTS;
    var logger = context.JK.logger;
    var rest = context.JK.Rest();
    var gearUtils = context.JK.GearUtils;
    var dialogId = '#audio-profile-invalid-dialog';
    var $dialog = null;
    var $results = null;
    var $resultsDetail = null;
    var $btnContinue = null;
    var $btnConfigureGear = null;
    var $btnRescan = null;
    var $btnRestartApplication = null;
    var $btnCancel = null;
    var reloadAudioTimeout = null;
    var rescanCount = 0;
    var cancelRescanFunc = null;

    function rescan() {
      // true = start back upaudio, true = auto load last used profile, false = don't reinit track assignments
      var result = context.jamClient.ReloadAudioSystem(true, true, false);
      rescanCount++;

      if(result.error) {

        $results.removeClass('success failed scanning').addClass('failed')
        $btnContinue.addClass('disabled')

        if(result.reason == "no_profile") {
          $results.removeClass('success failed scanning').addClass('failed')
          context.JK.Banner.showAlert('No Active Profile', 'Please select \'GO TO AUDIO GEAR SCREEN\' and activate a profile or add a new one.');
        }
        else {

          if(result.input) {
            $resultsDetail.append('<li>Input device is not functioning.</li>')
          }
          if(result.output) {
            $resultsDetail.append('<li>Output device is not functioning.</li>')
          }
          if(result.chat) {
            $resultsDetail.append('<li>Chat device is not functioning.</li>')
          }

          if(rescanCount >= 2) {
            $resultsDetail.append('<li>Tip: sometimes restarting JamKazam is necessary to clear up a device issue.</li>')
            $btnRestartApplication.show();
          }
        }
      }
      else {
        $results.removeClass('success failed scanning').addClass('success')
        $btnContinue.removeClass('disabled')
      }

    }
    function beforeShow() {
      $dialog.data('result', null);
      $results.removeClass('success failed scanning').addClass('scanning')
      $resultsDetail.empty();
      $btnContinue.addClass('disabled');
      $btnRestartApplication.hide();
      rescanCount  = 0;
    }

    function afterShow() {
      scheduleRescanSystem(500);
      context.JK.onBackendEvent(ALERT_NAMES.USB_CONNECTED, 'audio-profile-invalid-dialog', onUsbDeviceConnected);
      context.JK.onBackendEvent(ALERT_NAMES.USB_DISCONNECTED, 'audio-profile-invalid-dialog', onUsbDeviceDisconnected);
    }

    function onCancel() {
      if($btnCancel.is('.disabled')) return false;

      $dialog.data('result', 'cancel');
      return true;
    }

    function beforeHide() {
      context.JK.offBackendEvent(ALERT_NAMES.USB_CONNECTED, 'audio-profile-invalid-dialog', onUsbDeviceConnected);
      context.JK.offBackendEvent(ALERT_NAMES.USB_DISCONNECTED, 'audio-profile-invalid-dialog', onUsbDeviceDisconnected);
      cancelRescan();
    }

    function afterHide() {

    }

    function cancelRescan() {
      if(cancelRescanFunc) {
        cancelRescanFunc();
        cancelRescanFunc = null;
      }
    }

    function scheduleRescanSystem(time) {

      cancelRescanFunc = gearUtils.scheduleAudioRestart('audio-profile-invalid-dialog', time,
      function() {
        $resultsDetail.empty();
        $results.removeClass('success failed scanning').addClass('scanning')
        $dialog.find('a[data-purpose=reload-audio]').addClass('disabled')
        $dialog.find('.rescanning-notice').show();
      },
      function(canceled) {
        $results.removeClass('success failed scanning').addClass('scanning')
        $dialog.find('a[data-purpose=reload-audio]').removeClass('disabled')
        $dialog.find('.rescanning-notice').hide();
        if(!canceled){
          rescan();
        }
      })
    }

    function onUsbDeviceConnected() {
      if(!context.jamClient.IsFrontendVisible()) {return;} // don't handle USB events when minimized
      logger.debug("USB device connected");

      scheduleRescanSystem(3000);
    }

    function onUsbDeviceDisconnected() {
      if(!context.jamClient.IsFrontendVisible()) {return;} // don't handle USB events when minimized
      logger.debug("USB device disconnected");

      scheduleRescanSystem(3000);
    }
    
    function events() {
      $btnConfigureGear.click(function() {
        if($(this).is('.disabled')) return false;

        $dialog.data('result', 'configure_gear');
        app.layout.closeDialog('audio-profile-invalid-dialog');
        return false;
      })

      $btnRestartApplication.click(function() {
        if($(this).is('.disabled')) return false;

        context.JK.Banner.showYesNo({
          title: "Confirm Restart",
          html: "Are you sure you want to restart JamKazam?",
          yes: function() {
            context.jamClient.RestartApplication();
          },
          no : function() {
            context.JK.Banner.hide();
          }
        })
        return false;
      });

      $btnRescan.click(function() {
        if($(this).is('.disabled')) return false;

        scheduleRescanSystem(500);
        return false;
      })

      $btnContinue.click(function() {
        if($(this).is('.disabled')) return false;

        $dialog.data('result', 'session');
        app.layout.closeDialog('audio-profile-invalid-dialog');
        return false;
      })
    }

    function initialize() {

      var dialogBindings = {
        'beforeShow': beforeShow,
        'afterShow' : afterShow,
        'beforeHide' : beforeHide,
        'afterHide': afterHide,
        'onCancel' : onCancel
      };

      app.bindDialog('audio-profile-invalid-dialog', dialogBindings);

      $dialog = $(dialogId);
      $results = $dialog.find('.results');
      $resultsDetail = $dialog.find('.results-detail');
      $btnContinue = $dialog.find('.btnContinue');
      $btnConfigureGear = $dialog.find('.btnConfigureGear');
      $btnRescan = $dialog.find('a[data-purpose="reload-audio"]')
      $btnRestartApplication = $dialog.find('.btnRestartApplication');
      $btnCancel = $dialog.find('.btnCancel');

      events();
    }

    this.initialize = initialize;
  }

})(window, jQuery);