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.language.add(window.info.languagesJS);
  window.language.load('module/lpbc');
  window.containerNoInterestList = document.getElementById('container_no_interest');
  window.containerInterestList = document.getElementById('container_interest');

  const INTEREST = document.querySelector('.js-interest'),
    NO_INTEREST = document.querySelector('.js-no-interest'),
    CONTROLLER_OPTION = document.querySelector('.js-controller');

  CONTROLLER_OPTION.addEventListener('change', changeModule);

  function changeModule() {
    if (CONTROLLER_OPTION.value == 0) {
      NO_INTEREST.classList.remove('hidden');
      INTEREST.classList.add('hidden');
    } else {
      NO_INTEREST.classList.add('hidden');
      INTEREST.classList.remove('hidden');
    }
  }

  changeModule();

  document.getElementById('add_no_interest').onclick = addModuleNoInterest;
  document.getElementById('add_interest').onclick = addModuleInterest;

  const MODULES = window.info.modules;

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

  const MODULES_INTEREST = window.info.modules_interests;

  for (const key in MODULES_INTEREST) {
    addModuleInterest(MODULES_INTEREST[key]);
  }
}

function getLayout(context) {
  context = context = document;
  let modules = context.querySelectorAll('.js-module');
  for (let i = 0; i < modules.length; i++) {
    const MODULE = modules[i];
    const LAYOUT = MODULE.querySelector('.js-lpbc-layoutid');
    LAYOUT.onchange = handleProductLayout.bind(MODULE);
    LAYOUT.dispatchEvent(new Event('change'));
  }
}

function handleProductLayout() {
  const CATEGORY = this.querySelector('.js-lpbc-categoryid'),
    LAYOUT = this.querySelector('.js-lpbc-layoutid'),
    MESSAGE = document.createElement('span'),
    CONTROL_MESSAGE = this.querySelector('.js-message');

  MESSAGE.textContent = 'Serão exibidos os ultimos produtos da mesma categoria.';
  MESSAGE.setAttribute('class', 'text-small text-warning js-message');

  if (LAYOUT.value == 2) {
    CATEGORY.classList.add('hidden');
    CONTROL_MESSAGE ? '' : CATEGORY.after(MESSAGE);
  } else {
    CATEGORY.classList.remove('hidden');
    CONTROL_MESSAGE ? CONTROL_MESSAGE.remove() : '';
  }
}

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

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

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

let modulenoInterestId = '';
modulenoInterestId++;

let moduleInterestId = '';
moduleInterestId++;

function addModuleNoInterest(module = {}) {
  const { category_id, position, entry_type, limit, layout_id, status, sort_order } = module;

  const MODULE_NO_INTEREST_CONTAINER = document.createElement('div'),
    CATEGORIES = info.categories,
    POSITIONS = window.info.positions,
    TYPES = Type_DsimDnao.getEnumList(),
    LAYOUTS = info.layouts,
    STATUS = Type_Status.getEnumList(),
    ERROR_LIMIT = info.error_limit,
    ERROR_GRID = info.error_grid_limit,
    ERROR_SORT_ORDER = info.error_sort_order,
    HTML = `<div class="row x-small-space-xs">
    <div class="col-md">
      <label class="field field-medium">
        <span class="field-label">${language.get('entry_category')}</span>
        <select name="lpbc_module[${modulenoInterestId}][category_id]" class="field-entry js-lpbc-categoryid">
        ${CATEGORIES.map(
          category =>
            `<option value="${category.category_id}" ${category_id == category.category_id ? 'selected' : ''}>${
              category.name
            }</option>`
        ).join('')}
        </select>
      </label>
    </div>
    <div class="col-md">
      <label class="field field-medium">
        <span class="field-label">${language.get('entry_position')}</span>
        <select name="lpbc_module[${modulenoInterestId}][position]" class="field-entry js-control-position">
        ${Object.keys(POSITIONS)
          .map(key => `<option value="${key}" ${key == position ? 'selected' : ''}>${POSITIONS[key]}</option>`)
          .join('')}
        </select>
      </label>
    </div>
    <div class="col-md-width-auto">
      <label class="field field-medium">
        <span class="field-label">${language.get('entry_type')}</span>
        <select class="field-entry js-control-grid" name="lpbc_module[${modulenoInterestId}][entry_type]"
          ${position !== 'undefined' && position == 'column_left' ? 'disabled=true' : ''}>
          ${Object.keys(TYPES)
            .map(key => `<option value="${key}" ${key == entry_type ? 'selected' : ''}>${TYPES[key]}</option>`)
            .join('')}
        </select>
      </label>
    </div>
    <div class="col-md-width-auto">
      <label class="field field-medium">
        <span class="field-label">${language.get('entry_limit')}</span>
        <input type="text" name="lpbc_module[${modulenoInterestId}][limit]" size="1" class="field-entry js-control-limit mask-number2"
        value="${typeof limit !== 'undefined' ? limit : Type_DefaultValues.Tp_LimitModules24}"
        ${
          entry_type !== 'undefined' && entry_type == 0 && position !== 'undefined' && position != 'column_left'
            ? 'disabled=true'
            : ''
        }>
        ${
          ERROR_GRID[modulenoInterestId]
            ? `<span class="text-error text-small">${ERROR_GRID[modulenoInterestId]}</span>`
            : ''
        }
        ${
          ERROR_LIMIT[modulenoInterestId]
            ? `<span class="text-error text-small">${ERROR_LIMIT[modulenoInterestId]}</span>`
            : ''
        }
      </label>
    </div>
    <div class="col-md">
      <label class="field field-medium">
        <span class="field-label">${language.get('entry_layout')}</span>
        <select name="lpbc_module[${modulenoInterestId}][layout_id]" class="field-entry js-lpbc-layoutid">
        ${LAYOUTS.map(
          layout =>
            `<option value="${layout.layout_id}" ${layout_id == layout.layout_id ? 'selected' : ''}>${
              layout.name
            }</option>`
        ).join('')}
        </select>
      </label>
    </div>
    <div class="col-md">
      <label class="field field-medium">
        <span class="field-label">${language.get('entry_status')}</span>
        <select class="field-entry" name="lpbc_module[${modulenoInterestId}][status]">
        ${Object.keys(STATUS)
          .map(key => `<option value="${key}" ${status == key ? 'selected' : ''}>${STATUS[key]}</option>`)
          .join('')}
        </select>
      </label>
    </div>
    <div class="col-md-width-auto">
      <label class="field field-medium">
        <span class="field-label">${language.get('entry_sort_order')}</span>
        <input type="text" name="lpbc_module[${modulenoInterestId}][sort_order]"
        value="${typeof sort_order !== 'undefined' ? sort_order : 0}" size="1" class="field-entry mask-number2">
        ${
          ERROR_SORT_ORDER[modulenoInterestId]
            ? `<span class="text-error text-small">${ERROR_SORT_ORDER[modulenoInterestId]}</span>`
            : ''
        }
      </label>
    </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>`;

  MODULE_NO_INTEREST_CONTAINER.setAttribute(
    'class',
    'background-white padding-large bottom-margin-medium shadow-small adm-focus-within js-lpbc-content js-module'
  );
  MODULE_NO_INTEREST_CONTAINER.innerHTML = HTML;
  window.containerNoInterestList.prepend(MODULE_NO_INTEREST_CONTAINER);
  initRemove(MODULE_NO_INTEREST_CONTAINER);
  verifyTypeGrid(MODULE_NO_INTEREST_CONTAINER);
  getLayout(MODULE_NO_INTEREST_CONTAINER);

  modulenoInterestId++;
}

function addModuleInterest(module = {}) {
  const { position, entry_type, limit, layout_id, status, sort_order } = module;

  const MODULE_INTEREST_CONTAINER = document.createElement('div'),
    POSITIONS = window.info.positions,
    TYPES = Type_DsimDnao.getEnumList(),
    LAYOUTS = info.layouts,
    STATUS = Type_Status.getEnumList(),
    ERROR_LIMIT = info.error_limit,
    ERROR_GRID = info.error_grid_limit,
    ERROR_SORT_ORDER = info.error_sort_order,
    HTML = `<div class="row x-small-space-xs">
    <div class="col-md">
      <label class="field field-medium">
        <span class="field-label">${language.get('entry_position')}</span>
        <select name="lpbc_module_interests[${moduleInterestId}][position]" class="field-entry js-control-position">
        ${Object.keys(POSITIONS)
          .map(key => `<option value="${key}" ${key == position ? 'selected' : ''}>${POSITIONS[key]}</option>`)
          .join('')}
        </select>
      </label>
    </div>
    <div class="col-md-width-auto">
      <label class="field field-medium">
        <span class="field-label">${language.get('entry_type')}</span>
        <select class="field-entry js-control-grid" name="lpbc_module_interests[${moduleInterestId}][entry_type]"
        ${position !== 'undefined' && position == 'column_left' ? 'disabled=true' : ''}>
        ${Object.keys(TYPES)
          .map(key => `<option value="${key}" ${key == entry_type ? 'selected' : ''}>${TYPES[key]}</option>`)
          .join('')}
        </select>
      </label>
    </div>
    <div class="col-md-width-auto">
      <label class="field field-medium">
        <span class="field-label">${language.get('entry_limit')}</span>
        <input type="text" name="lpbc_module_interests[${moduleInterestId}][limit]" size="1" class="field-entry js-control-limit mask-number2"
        value="${typeof limit !== 'undefined' ? limit : Type_DefaultValues.Tp_LimitModules24}"
        ${entry_type == 0 && position !== 'column_left' ? 'disabled=true' : ''}>
        ${
          ERROR_GRID.moduleInterestId ? `<span class="text-error text-small">${ERROR_GRID.moduleInterestId}</span>` : ''
        }
        ${
          ERROR_LIMIT.moduleInterestId
            ? `<span class="text-error text-small">${ERROR_LIMIT.moduleInterestId}</span>`
            : ''
        }
      </label>
    </div>
    <div class="col-md">
      <label class="field field-medium">
        <span class="field-label">${language.get('entry_layout')}</span>
        <select class="field-entry" name="lpbc_module_interests[${moduleInterestId}][layout_id]">
        ${LAYOUTS.filter(({ layout_id }) => {
          return layout_id != Type_IdLayout.Tp_IdProduct && layout_id != Type_IdLayout.Tp_Idcategory;
        })
          .map(
            layout =>
              `<option value="${layout.layout_id}" ${layout_id == layout.layout_id ? 'selected' : ''}>${
                layout.name
              }</option>`
          )
          .join('')}
        </select>
      </label>
    </div>
    <div class="col-md">
      <label class="field field-medium">
        <span class="field-label">${language.get('entry_status')}</span>
        <select class="field-entry" name="lpbc_module_interests[${moduleInterestId}][status]">
        ${Object.keys(STATUS)
          .map(key => `<option value="${key}" ${status == key ? 'selected' : ''}>${STATUS[key]}</option>`)
          .join('')}
        </select>
      </label>
    </div>
    <div class="col-md-width-auto">
      <label class="field field-medium">
        <span class="field-label">${language.get('entry_sort_order')}</span>
        <input type="text" name="lpbc_module_interests[${moduleInterestId}][sort_order]"
        value="${typeof sort_order !== 'undefined' ? sort_order : 0}" size="1" class="field-entry mask-number2">
        ${
          ERROR_SORT_ORDER[moduleInterestId]
            ? `<span class="text-error text-small">${ERROR_SORT_ORDER[moduleInterestId]}</span>`
            : ''
        }
      </label>
    </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>`;

  MODULE_INTEREST_CONTAINER.setAttribute(
    'class',
    'background-white padding-large bottom-margin-medium shadow-small adm-focus-within js-lpbc-content js-module'
  );
  MODULE_INTEREST_CONTAINER.innerHTML = HTML;
  window.containerInterestList.prepend(MODULE_INTEREST_CONTAINER);
  initRemove(MODULE_INTEREST_CONTAINER);
  verifyTypeGrid(MODULE_INTEREST_CONTAINER);

  moduleInterestId++;
}
