/*
 * This file is part of the Sylius package.
 *
 * (c) Paweł Jędrzejewski
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

/* eslint-env browser */

const parseKey = function parseKey(key) {
  return key.replace(/(_\w)/g, (words) => words[1].toUpperCase());
};

const SyliusAddressBook = function SyliusAddressBook(el) {
  const element = el;
  const select = element.querySelector('.dropdown');
  const findByName = function findByName(name) {
    return element.querySelector(`[name*=${parseKey(name)}]`);
  };
  const changeEvent = new Event('change');

  select.querySelectorAll('.dropdown-item').forEach((item) => {
    item.addEventListener('click', (e) => {
      const choice = e.currentTarget;
      const choiceData = {};

      [...choice.attributes].forEach((attr) => {
        if (attr.name.startsWith('data-')) {
          const camelCased = attr.name.replace('data-', '').replace(/-([a-z])/g, (g) => g[1].toUpperCase());
          choiceData[camelCased] = attr.value;
        }
      });

      const { provinceCode, provinceName } = choiceData;
      const provinceContainer = el.querySelector('.province-container');

      element.querySelectorAll('input, select').forEach((input) => {
        // eslint-disable-next-line no-param-reassign
        input.value = '';
      });

      Object.entries(choiceData).forEach(([property, value]) => {
        const field = findByName(property);

        if (property.indexOf('countryCode') !== -1) {
          field.value = value;
          field.dispatchEvent(changeEvent);

          const exists = setInterval(() => {
            const provinceCodeField = findByName('provinceCode');
            const provinceNameField = findByName('provinceName');

            if (!provinceContainer.hasAttribute('data-loading')) {
              if (provinceCodeField && provinceCodeField.length !== 0 && (provinceCode !== '' || provinceCode !== undefined)) {
                provinceCodeField.value = provinceCode;

                clearInterval(exists);
              } else if (provinceNameField && provinceNameField.length !== 0 && (provinceName !== '' || provinceName !== undefined)) {
                provinceNameField.value = provinceName;

                clearInterval(exists);
              }
            }
          }, 100);
        } else if (field) {
          field.value = value;
        }
      });
    });
  });
};

export default SyliusAddressBook;
