'use strict';

import axios from 'axios';
import { maskCep } from '../../../../../../../../../assets/js/masks';

window.waitEvent('window', function() {
  const RESELLER = document.getElementById('reseller'),
    FIELD_RESELLER = RESELLER.querySelector('.js-field-search'),
    CONTENT_RESELLER = RESELLER.querySelector('.js-reseller-content');

  maskCep(FIELD_RESELLER);

  handleButton();

  function handleButton() {
    const BUTTONS_RESELLER = RESELLER.querySelectorAll('.js-btn-reseller');

    for (let i = 0; i < BUTTONS_RESELLER.length; i++) {
      const BUTTON = BUTTONS_RESELLER[i];
      BUTTON.onclick = handleSearchReseller;
    }
  }

  function handleSearchReseller() {
    const THIS = this,
      PARENT = FIELD_RESELLER.parentNode.parentNode.parentNode;

    if (FIELD_RESELLER.value.length < 9) {
      PARENT.classList.add('field-error');
      return false;
    } else {
      PARENT.classList.remove('field-error');
    }

    THIS.classList.add('btn-loading');

    const DIV = document.createElement('div');
    DIV.classList.add('padding-large');
    DIV.classList.add('border-gray');
    DIV.classList.add('text-center');
    DIV.classList.add('top-margin-medium');

    const SPAN = document.createElement('span');
    SPAN.classList.add('visible-block');
    SPAN.classList.add('text-x-large');
    SPAN.classList.add('text-dark');
    SPAN.classList.add('margin-x-large');
    SPAN.textContent = 'Buscando...';

    DIV.appendChild(SPAN);

    CONTENT_RESELLER.innerHTML = '';
    CONTENT_RESELLER.appendChild(DIV);

    const FORM_DATA = new FormData();
    FORM_DATA.append('cep', FIELD_RESELLER.value);
    FORM_DATA.append('page', typeof this.dataset.page === 'undefined' ? 1 : this.dataset.page);

    axios({
      method: 'post',
      url: 'index.php?route=information/reseller/search',
      data: FORM_DATA,
    }).then(function({ data }) {
      CONTENT_RESELLER.innerHTML = data;
      THIS.classList.remove('btn-loading');
      handleButton();
    });
  }
});
