if (document.readyState === 'complete') {
  init();
} else {
  document.addEventListener('DOMContentLoaded', function() {
    init();
  });
}

function init() {
  window.info = JSON.parse(document.querySelector('[data-info]').getAttribute('data-info'));
  window.containerModuleList = document.getElementById('container_modules');

  window.language.add(window.info.languagesJS);
  window.language.load('module/product_visualized');

  document.getElementById('add_module').onclick = addModule;

  const MODULES = window.info.modules;

  for (const key in MODULES) {
    addModule(MODULES[key]);
  }

  initChangeModuleStatus();
}

function initRemoveModule(context) {
  context = context || document;
  let removeButtons = context.querySelectorAll('.js-remove-module');
  for (let i = 0; i < removeButtons.length; i++) {
    removeButtons[i].onclick = removeModule;
  }
}

function removeModule() {
  this.closest('.js-module-row').remove();
}

function controlGrid(context) {
  context = context || document;
  let gridEntries = context.querySelectorAll('.js-control-grid');
  for (let i = 0; i < gridEntries.length; i++) {
    const GRID = gridEntries[i];
    GRID.dispatchEvent(new Event('change', { bubbles: true }));
  }
}

function initChangeModuleStatus() {
  const STATUS_MODULE = document.querySelector('.js-product-visualized-status');
  STATUS_MODULE.onchange = changeModuleStatus;
  STATUS_MODULE.dispatchEvent(new Event('change'));
}

function changeModuleStatus() {
  let status = this.value;
  let modulesStatuses = document.querySelectorAll('.js-module-visualized-status');

  for (let i = 0; i < modulesStatuses.length; i++) {
    const MODULE = modulesStatuses[i];
    MODULE.value = status;
  }
}

let moduleId = '';
moduleId++;

function addModule(module = {}) {
  const { layout_id, position, limit, entry_type, sort_order, status } = module;
  const CONTAINER_MODULE = document.createElement('div'),
    POSITIONS = window.info.positions,
    TYPES = Type_DsimDnao.getEnumList(),
    LAYOUTS = window.info.layouts,
    STATUS = Type_Status.getEnumList(),
    ERROR_LIMIT = window.info.error_limit,
    ERROR_GRID = window.info.error_grid_limit,
    ERROR_SORT_ORDER = window.info.error_sort_order,
    HTML = `<div class="row x-small-space-xs">
      <div class="col-md">
        <span class="field-label">${language.get('entry_position')}</span>
        <select name="product_visualized_module[${moduleId}][position]" class="field-entry js-control-position">
        ${Object.keys(POSITIONS)
          .map(key => `<option value="${key}" ${key == position ? 'selected' : ''}>${POSITIONS[key]}</option>`)
          .join('')}
        </select>
      </div>
      <div class="col-md">
        <span class="field-label">${language.get('entry_type')}</span>
        <select class="field-entry js-control-grid" name="product_visualized_module[${moduleId}][entry_type]"
          ${position !== 'undefined' && position == Type_ModulePosition.Tp_ColumnLeft ? 'disabled=true' : ''}>
          ${Object.keys(TYPES)
            .map(key => `<option value="${key}" ${key == entry_type ? 'selected' : ''}>${TYPES[key]}</option>`)
            .join('')}
        </select>
      </div>
      <div class="col-md-width-auto">
        <span class="field-label">${language.get('entry_limit')}</span>
        <input type="text" class="field-entry js-control-limit mask-number2" size="1" name="product_visualized_module[${moduleId}][limit]"
          ${
            entry_type !== 'undefined' &&
            entry_type == Type_DsimDnao.Tp_Nao &&
            position !== 'undefined' &&
            position != Type_ModulePosition.Tp_ColumnLeft
              ? 'disabled=true'
              : ''
          }
          value="${typeof limit !== 'undefined' ? limit : Type_DefaultValues.Tp_LimitModules24}">
        ${ERROR_GRID[moduleId] ? `<span class="text-error text-small">${ERROR_GRID[moduleId]}</span>` : ''}
        ${ERROR_LIMIT[moduleId] ? `<span class="text-error text-small">${ERROR_LIMIT[moduleId]}</span>` : ''}
      </div>
      <div class="col-md">
        <span class="field-label">${language.get('entry_layout')}</span>
        <select class="field-entry" name="product_visualized_module[${moduleId}][layout_id]">
          ${LAYOUTS.map(
            layout =>
              `<option value="${layout.layout_id}" ${layout_id == layout.layout_id ? 'selected' : ''}>${
                layout.name
              }</option>`
          ).join('')}
        </select>
      </div>
      <div class="hidden">
        <select class="field-entry js-module-visualized-status" name="product_visualized_module[${moduleId}][status]">
        ${Object.keys(STATUS)
          .map(key => `<option value="${key}" ${key == status ? 'selected' : ''}>${STATUS[key]}</option>`)
          .join('')}
        </select>
      </div>
      <div class="col-md-width-auto">
        <span class="field-label">${language.get('entry_sort_order')}</span>
        <input class="field-entry mask-number2" type="text" name="product_visualized_module[${moduleId}][sort_order]"
        value="${typeof sort_order !== 'undefined' ? sort_order : 0}" size="1">
        ${
          ERROR_SORT_ORDER[moduleId]
            ? `<span class="text-error text-small">{{ error_sort_order[module_row] }}</span>`
            : ''
        }
      </div>
      <div class="col-xs-12 col-md-width-auto">
        <div class="padding-medium cursor-pointer top-margin-medium js-remove-module"
        data-tooltip="${language.get('button_remove')}"
        >
          <i class="fas fa-trash text-gray"></i>
        </div>
      </div>
    </div>`;

  CONTAINER_MODULE.setAttribute(
    'class',
    'background-white padding-large shadow-small adm-focus-within bottom-margin-medium js-module-row'
  );
  CONTAINER_MODULE.innerHTML = HTML;
  window.containerModuleList.prepend(CONTAINER_MODULE);
  initRemoveModule(CONTAINER_MODULE);
  controlGrid(CONTAINER_MODULE);
  initChangeModuleStatus();

  moduleId++;
}
