/*
 * Copyright (c) 2018-2019, 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');

  this.form = Prime.Document.queryById('application-form');

  // This field is not available on the FusionAuth application
  this.deviceGrantCheckbox = this.form.queryFirst('input[value=device_code]');
  if (this.deviceGrantCheckbox !== null) {
    this.deviceGrantCheckbox.addEventListener('change', this._handleDeviceGrantChange);
    this.deviceVerificationURL = Prime.Document.queryById('device-verification-url');
  }

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

  new FusionAuth.Admin.OAuthConfiguration(Prime.Document.queryFirst('form'));
  new Prime.Widgets.Tabs(Prime.Document.queryFirst('.tabs'))
      .withErrorClassHandling('error')
      .withLocalStorageKey(this.addApplication ? null : 'applications.tabs')
      .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 change on the Device Authorization grant checkbox.
   *
   * @returns {boolean} Always true.
   * @private
   */
  _handleDeviceGrantChange: function() {
    // Find the Device Grant checkbox, show the Device Verification URL input if checked
    if (this.deviceGrantCheckbox.isChecked()) {
      this.deviceVerificationURL.addClass('open');
    } else {
      this.deviceVerificationURL.removeClass('open');
    }
  },
};
