/*
 * Copyright (c) 2018, FusionAuth, All Rights Reserved
 */
'use strict';

var FusionAuth = FusionAuth || {};
FusionAuth.Admin = FusionAuth.Admin || {};

/**
 * Handles the add and edit application form. The row table is managed by the ExpandableTable object.
 *
 * @constructor
 */
FusionAuth.Admin.ApplicationForm = function() {
  Prime.Utils.bindAll(this);

  this.cleanSpeakUsernameModerationCheckbox = Prime.Document.queryById('application_cleanSpeakConfiguration_usernameModeration_enabled');
  this.cleanSpeakUsernameSettings = Prime.Document.queryById('clean-speak-settings');

  var formAction = Prime.Document.queryById('application-form').getAttribute('action');
  this.addApplication = formAction === '/admin/application/add';

  this.jwtConfiguration = new FusionAuth.Admin.JWTConfiguration(Prime.Document.queryById('jwt-settings'));

  new FusionAuth.Admin.OAuthConfiguration(Prime.Document.queryFirst('form'));
  new Prime.Widgets.Tabs(Prime.Document.queryFirst('.tabs'))
      .withErrorClassHandling('error')
      .withLocalStorageKey(this.addApplication ? null : 'application-configuration')
      .withSelectCallback(this._handleTabSelect)
      .initialize();

  // Setup the role table
  if (this.addApplication) {
    new FusionAuth.UI.ExpandableTable(Prime.Document.queryById('role-table'));
  }

  if (this.cleanSpeakUsernameModerationCheckbox !== null) {
    this.cleanSpeakUsernameModerationCheckbox.addEventListener('click', this._handleCleanSpeakClick);
    this._handleCleanSpeakClick();
  }
};

FusionAuth.Admin.ApplicationForm.prototype = {
  /**
   * Handles the CleanSpeak enable checkbox click.
   *
   * @returns {boolean} Always true.
   * @private
   */
  _handleCleanSpeakClick: function() {
    if (this.cleanSpeakUsernameModerationCheckbox.isChecked()) {
      this.cleanSpeakUsernameSettings.show();
    } else {
      this.cleanSpeakUsernameSettings.hide();
    }

    return true;
  },

  /**
   * Handles the tab selection.
   *
   * @param {Element} tab The &lt;li> tab element that was selected.
   * @param {Element} tabContent The &lt;div> that contains the tab contents.
   * @private
   */
  _handleTabSelect: function(tab, tabContent) {
    if (tabContent.getId() === 'jwt-settings') {
      this.jwtConfiguration.onTabShown();
    }
  }
};
