import '@babel/polyfill';
import axios from 'axios';
import { renderHtml } from './helpers';

export class searchPostcode {
  constructor(postcode, { baseUrl, hiddenClass }) {
    this.postcode = postcode;
    this.baseUrl = baseUrl;
    this.hiddenClass = hiddenClass;

    this.html = this.getHtml();
    this.init();
  }
  init() {
    this.add();
    this.modalContent = this.html.querySelector('.js-postcode-content-overlay');

    // impede que o click no modal propague para o overlay,
    // porque o clique no overlay fecha o modal
    this.modalContent.addEventListener('click', e => e.stopPropagation());

    this.getModalContent()
      .then(({ data }) => {
        if (data) {
          this.modalContent.innerHTML = data;

          this.getElements();
          this.close = Array.from(this.close);
          this.close.push(this.html); // adiciona o overlay

          this.inputSearch.focus();

          this.initEvents();
          this.initCloseEvents();
        }
      })
      .catch(error => console.error(error));
  }
  initEvents() {
    this.inputSearch.addEventListener('keyup', e => {
      if (e.keyCode == '13') this.btnSearch.dispatchEvent(new Event('click'));
    });

    this.btnSearch.addEventListener('click', () => {
      this.searchLoadingStart();
      this.btnApply.disabled = true;

      this.getPostcodeList()
        .then(({ data }) => {
          if (data) {
            this.resultContainer.innerHTML = data;
            const OPTIONS = this.resultContainer.querySelectorAll('input[name=address]');
            this.initListOptionsEvents(OPTIONS);
          }
        })
        .catch(error => console.error(error))
        .finally(() => this.searchLoadingEnd());
    });

    this.btnApply.addEventListener('click', () => this.applyPostcode());
  }
  initCloseEvents() {
    for (let index = 0; index < this.close.length; index++) {
      this.close[index].addEventListener('click', e => {
        e.preventDefault();
        this.remove();
      });
    }
  }
  initListOptionsEvents(options) {
    for (let index = 0; index < options.length; index++) {
      options[index].addEventListener('click', () => {
        this.btnApply.disabled = false;
      });
    }
  }
  getElements() {
    this.inputSearch = this.html.querySelector('#search_address');
    this.btnSearch = this.html.querySelector('.js-postcode-list-address');
    this.btnApply = this.html.querySelector('.js-postcode-apply');
    this.resultContainer = this.html.querySelector('.js-result-postcode-address');
    this.close = this.html.querySelectorAll('.js-postcode-cancel, .js-postcode-close');
    this.searchLoading = this.getLoadingSearch();
  }
  getLoadingSearch() {
    return this.html.querySelector('.js-postcode-address-loading');
  }
  getHtml() {
    return renderHtml(`
    <div class="overlay overlay-black-3 js-postcode-overlay" style="z-index:100">
      <div class="flex middle-xs center-xs shadow-small center-middle-fixed background-white js-postcode-content-overlay" style="width: 100%; max-width: 400px; min-height: 400px;">

          <img src="${this.baseUrl}/assets/img/loading-black.svg" class="full-width" width="60" height="60">

      </div>
    </div>
    `);
  }
  getModalContent() {
    return axios({
      headers: { 'content-type': 'application/x-www-form-urlencoded' },
      url: this.baseUrl + 'index.php?route=postcode/postcode',
      method: 'post',
      timeout: 10000,
    });
  }
  getPostcodeList() {
    return axios({
      headers: { 'content-type': 'application/x-www-form-urlencoded' },
      url: this.baseUrl + 'index.php?route=postcode/postcode/listAddress',
      method: 'post',
      timeout: 10000,
      data: 'dados=' + this.inputSearch.value,
    });
  }
  applyPostcode() {
    const DataPostcode = this.html.querySelector('input[name=address]:checked').dataset.postcode;

    this.postcode.value = ('000000000' + DataPostcode).slice(-9);
    this.postcode.focus();
    this.postcode.dispatchEvent(new Event('keyup', { bubbles: true }));
    this.remove();
  }
  add() {
    document.body.appendChild(this.html);
  }
  remove() {
    this.html.parentNode.removeChild(this.html);
  }
  searchLoadingStart() {
    this.resultContainer.style.opacity = 0.3;
    this.searchLoading.classList.remove(this.hiddenClass);
  }
  searchLoadingEnd() {
    this.resultContainer.style.opacity = 1;
    this.searchLoading.classList.add(this.hiddenClass);
  }
}

export class searchPostcodeApp extends searchPostcode {
  init() {
    this.getElements();
    this.initEvents();
  }
  getLoadingSearch() {
    return document.querySelector('.ftr-loading-bar');
  }
  getHtml() {
    return document.getElementById('dont_know_cep');
  }
  remove() {
    this.close[0].dispatchEvent(new Event('click', { bubbles: true }));
  }
}
