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

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

/**
 * Provides additional features to the ExpandableTable to support localization tables where one of the columns is a
 * select box with the locales and the other is a text field.
 *
 * @param {Prime.Document.Element} table The table element.
 * @constructor
 */
FusionAuth.Admin.LocalizationTable = function(table) {
  Prime.Utils.bindAll(this);

  new FusionAuth.UI.ExpandableTable(table).withAddCallback(this._addCallback);
  Prime.Document.query('select', table).each(function(e) {
    e.addEventListener('change', this._handleSelectChangeEvent);
  }.bind(this));
};

FusionAuth.Admin.LocalizationTable.prototype = {
  /**
   * @private
   */
  _addCallback: function(row) {
    Prime.Document.queryFirst('select', row).addEventListener('change', this._handleSelectChangeEvent);
  },

  /**
   * @private
   */
  _handleSelectChangeEvent: function(event) {
    var select = new Prime.Document.Element(event.currentTarget);
    var row = Prime.Document.queryUp('tr', select);
    Prime.Document.query('input', row).each(function(inputElement) {
      var name = inputElement.getAttribute('name');
      var startIndex = name.indexOf("['");
      var newName = name.substring(0, startIndex) + "['" + select.getSelectedValues()[0] + "']";
      inputElement.setAttribute('name', newName);
    });

    Prime.Document.query('textarea', row).each(function(inputElement) {
      var name = inputElement.getAttribute('name');
      var startIndex = name.indexOf("['");
      var newName = name.substring(0, startIndex) + "['" + select.getSelectedValues()[0] + "']";
      inputElement.setAttribute('name', newName);
    });
  }
};

