/*
  globals HelperModule animateSpinner SmartAnnotation Asset
*/
/* eslint-disable no-unused-vars */

var RepositoryDatatableRowEditor = (function() {
  const NAME_COLUMN_ID = 'row-name';
  const TABLE_ROW = '<tr></tr>';
  const TABLE_CELL = '<td></td>';

  var TABLE;

  // Initialize SmartAnnotation
  function initSmartAnnotation($row) {
    $row.find('[data-object="repository_cell"]').each(function(el) {
      if (el.data('atwho')) {
        SmartAnnotation.init(el);
      }
    });
  }

  function validateAndSubmit($table) {
    let $form = $table.find('.repository-row-edit-form');
    let $row = $form.closest('tr');
    let valid = true;
    let directUrl = $table.data('direct-upload-url');
    let $files = $row.find('input[type=file]');
    $row.find('.has-error').removeClass('has-error').find('span').remove();

    // Validations here
    $row.find('input').each(function() {
      let dataType = $(this).data('type');
      if (!dataType) return;

      valid = $.fn.dataTable.render[dataType + 'Validator']($(this));
      if (!valid) return false;
    });

    if (!valid) return false;

    // DirectUpload here
    let uploadPromise = Asset.uploadFiles($files, directUrl);

    // Submission here
    uploadPromise
      .then(function() {
        animateSpinner(null, true);
        $form.submit();
        return false;
      }).catch((reason) => {
        alert(reason);
        return false;
      });

    return null;
  }

  function initAssetCellActions($row) {
    let fileInputs = $row.find('input[type=file]');
    let deleteButtons = $row.find('.file-upload-button>span.delete-action');

    fileInputs.on('change', function() {
      let $input = $(this);
      let $fileBtn = $input.next('.file-upload-button');
      let $label = $fileBtn.find('.label-asset');

      $label.text($input[0].files[0].name);
      $fileBtn.removeClass('new-file');
      $fileBtn.removeClass('error');
    });


    deleteButtons.on('click', function() {
      let $fileBtn = $(this).parent();
      let $input = $fileBtn.prev('input[type=file]');
      let $label = $fileBtn.find('.label-asset');

      $fileBtn.addClass('new-file');
      $label.text('');
      $input.val('');
      $fileBtn.removeClass('error');

      if (!$input.data('is-empty')) { // set hidden field for deletion only if original value has been set on rendering
        $input
          .prev('.file-hidden-field-container')
          .html(`<input type="hidden"
                     form="${$input.attr('form')}"
                     name="repository_cells[${$input.data('col-id')}]"
                     value=""/>`);
      }
    });
  }

  function initFormSubmitAction(table) {
    TABLE = table;
    let $table = $(TABLE.table().node());

    $table.on('ajax:success', '.repository-row-edit-form', function(ev, data) {
      TABLE.ajax.reload(() => {
        animateSpinner(null, false);
        HelperModule.flashAlertMsg(data.flash, 'success');

        setTimeout(() => {
          window.scrollTo({
            left: 0,
            behavior: 'smooth'
          });
        }, 400);
      });
    });

    $table.on('ajax:error', '.repository-row-edit-form', function(ev, data) {
      animateSpinner(null, false);
      HelperModule.flashAlertMsg(data.responseJSON.flash, 'danger');
    });
  }

  function addNewRow(table) {
    TABLE = table;

    let $row = $(TABLE_ROW);
    const formId = 'repositoryNewRowForm';
    let actionUrl = $(TABLE.table().node()).data('createRecord');
    let rowForm = $(`
      <td>
        <form id="${formId}"
              class="repository-row-edit-form"
              action="${actionUrl}"
              method="post"
              data-remote="true">
        </form>
      </td>
    `);

    // First two columns are always present and visible
    $row.append(rowForm);
    $row.append($(TABLE_CELL));

    $(TABLE.table().node()).find('tbody').prepend($row);

    table.columns().every(function() {
      let column = this;
      let $header = $(column.header());

      if (column.index() < 2) return;
      if (!column.visible()) return;

      let columnId = $header.attr('id');

      let $cell = $(TABLE_CELL).appendTo($row);

      if (columnId === NAME_COLUMN_ID) {
        $.fn.dataTable.render.newRowName(formId, $cell);
      } else {
        let dataType = $header.data('type');
        if (dataType) {
          $.fn.dataTable.render['new' + dataType](formId, columnId, $cell, $header);
        }
      }
    });

    initSmartAnnotation($row);
    initAssetCellActions($row);

    TABLE.columns.adjust();
  }

  function switchRowToEditMode(row) {
    let $row = $(row.node());
    let itemId = row.id();
    let formId = `repositoryRowForm${itemId}`;
    let requestUrl = $(TABLE.table().node()).data('current-uri');
    let rowForm = $(`
      <form id="${formId}"
            class="repository-row-edit-form"
            action="${row.data().recordUpdateUrl}"
            method="patch"
            data-remote="true"
            data-row-id="${itemId}">
        <input name="id" type="hidden" value="${itemId}" />
        <input name="request_url" type="hidden" value="${requestUrl}" />
      </form>
    `);

    $row.find('td').first().append(rowForm);

    TABLE.cells(row.index(), row.columns().eq(0)).every(function() {
      let $header = $(TABLE.columns(this.index().column).header());
      let columnId = $header.attr('id');
      let dataType = $header.data('type');
      let cell = this;

      if (!cell.column(cell.index().column).visible()) return true; // return if cell is not visible

      if (columnId === NAME_COLUMN_ID) {
        $.fn.dataTable.render.editRowName(formId, cell);
      } else if (dataType) {
        $.fn.dataTable.render['edit' + dataType](formId, columnId, cell, $header);
      }

      return true;
    });

    initSmartAnnotation($row);
    initAssetCellActions($row);

    TABLE.columns.adjust();
  }

  return Object.freeze({
    initFormSubmitAction: initFormSubmitAction,
    validateAndSubmit: validateAndSubmit,
    switchRowToEditMode: switchRowToEditMode,
    addNewRow: addNewRow
  });
}());

@@ -2941,25 +2941,24 @@
 cess');%0A
-%0A
         
 setTimeo
@@ -2953,133 +2953,50 @@
     
-setTimeout(() =%3E %7B%0A          window.scrollTo(%7B%0A            left: 0,%0A            behavior: 'smooth'%0A          %7D);%0A        %7D, 4
+$('html, body').animate(%7BscrollLeft: 0%7D, 3
 00);

Use Jquery scroll