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

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

/**
 * Handles the system configuration form.
 *
 * @constructor
 */
FusionAuth.Admin.SystemConfigurationForm = function() {
  Prime.Utils.bindAll(this);

  this.verifyEmailCheckbox = Prime.Document.queryById(
      'systemConfiguration_emailConfiguration_verifyEmail').addEventListener('click', this._handleVerifyEmailClick);
  this.emailSettings = Prime.Document.queryById('email-verification-settings');

  this.failedAuthenticationUserAction = Prime.Document.queryById(
      'systemConfiguration_failedAuthenticationConfiguration_userActionId').addEventListener('change',
      this._handleFailedAuthenticationUserActionChange);
  this.failedAuthenticationSettings = Prime.Document.queryById('failed-authentication-options');

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

  this.minimumPasswordAge = Prime.Document.queryById('systemConfiguration_minimumPasswordAge');

  // Create all the editors and put them in a hash keyed of the name (which is the id of the tab)
  this.editors = {};
  ['emailComplete', 'emailSend', 'emailVerify', 'oauth2Authorize', 'oauth2Error', 'oauth2TwoFactor', 'passwordChange',
    'passwordComplete', 'passwordForgot', 'passwordSent', 'registrationComplete', 'registrationSend', 'registrationVerify',
    'helpers'].forEach(function(name) {
    var element = Prime.Document.queryFirst('textarea[name="systemConfiguration.uiConfiguration.loginTheme.' + name + '"]');
    this.editors[name] = new FusionAuth.UI.TextEditor(element).withOptions({'mode': 'freemarker', 'lineWrapping': true});
  }.bind(this));

  // Add the CSS editor
  this.editors['stylesheet'] =
      new FusionAuth.UI.TextEditor(Prime.Document.queryFirst('textarea[name="systemConfiguration.uiConfiguration.loginTheme.stylesheet"]'))
          .withOptions({'mode': 'css', 'lineWrapping': true});

  this._handleFailedAuthenticationUserActionChange();
  this._handleVerifyEmailClick();

  this.uiTabs = null; // Default to null and then set it up later
  new Prime.Widgets.Tabs(Prime.Document.queryById('tabs'))
      .withErrorClassHandling('error')
      .withSelectCallback(this._handleTabSelect)
      .withLocalStorageKey('system-configuration')
      .initialize();
};

FusionAuth.Admin.SystemConfigurationForm.prototype = {

  /* ===================================================================================================================
   * Private methods
   * ===================================================================================================================*/

  _handleFailedAuthenticationUserActionChange: function() {
    if (this.failedAuthenticationUserAction.getValue() === '') {
      this.failedAuthenticationSettings.hide();
    } else {
      this.failedAuthenticationSettings.show();
    }
  },

  _handleTabSelect: function(tab, tabContent) {
    if (tabContent.getId() === 'jwt-settings') {
      this.jwtConfiguration.onTabShown();
    } else if (tabContent.getId() === 'ui-settings') {
      console.log("UI tab and " + this.uiTabs);
      if (this.uiTabs === null) {
        this.uiTabs = new Prime.Widgets.Tabs(Prime.Document.queryById('ui-tabs'))
            .withErrorClassHandling('error')
            .withSelectCallback(this._handleUITabSelect)
            .withLocalStorageKey('system-configuration-ui-tabs')
            .initialize();
      }
    }
  },

  _handleUITabSelect: function(tab, tabContent) {
    this.editors[tabContent.getId()].render().setHeight(600);
  },

  _handleVerifyEmailClick: function() {
    if (this.emailSettings === null) {
      return;
    }

    if (this.verifyEmailCheckbox.isChecked()) {
      this.emailSettings.show();
    } else {
      this.emailSettings.hide();
    }
  }
};
