import $ from 'jquery';

class IHKSurvey {
  constructor(section) {
    this.section = section.addClass('initiated');
    this.formBox = section.find('.form-box');
    this.form = section.find('form');

    this.initSize();

    if (this.form.data('show-result')) {
      this.loadResult();
    }
    else {
      this.initOptions();
    }
  }

  initSize() {
    const observer = new ResizeObserver((entries) => {
      entries.map((entry) => {
        const w = entry.borderBoxSize[0].inlineSize;

        window.requestAnimationFrame(() => {
          if (w < 500) {
            this.section.attr('data-size', 'sm');
          } else if (w < 1000) {
            this.section.attr('data-size', 'md');
          } else {
            this.section.attr('data-size', 'lg');
          }
        })
      })
    })
    observer.observe(this.section.get(0));
  }

  initOptions() {
    this.form.find('input[type="radio"]').on('change', (e) => {
      if (this.form.find('input[type="radio"]:checked').length === this.form.find('fieldset').length) {
        this.loadResult();
      }
    })
  }

  loadResult() {
    if (this.form.attr('method') === 'get') {
      $.get(this.form.attr('action'), this.form.serialize()).done((result) => {
        this.insertResult(result);
      })
    } else {
      $.post(this.form.attr('action'), this.form.serialize()).done((result) => {
        this.insertResult(result);
      })
    }
  }

  insertResult(result) {
    const heightDiff = this.formBox.outerHeight() - this.form.outerHeight();
    this.formBox.css('height', this.formBox.outerHeight() + 'px');

    this.result = $(result).appendTo(this.formBox);
    this.formBox.css('height', (this.result.outerHeight() + heightDiff) + 'px');
    this.animateResult();

    setTimeout(() => {
      this.section.addClass('show-result');
    },50)

    setTimeout(() => {
      this.formBox.removeAttr('style');
    },800)
  }

  animateResult() {
    const items = this.result.find('.sub-result-wrapper');

    items.each((i, el) => {
      $('<span class="bar" />').prependTo($(el)).css('transition-delay', (i / 10).toString() + 's');
    })

    setTimeout(() => {
      items.each((i, el) => {
        const item = $(el);
        item.find('.bar').css('width', parseInt(item.find('.value').text()) + '%');
      })
    },500)
  }
}

export default IHKSurvey;

$('body').on('ihk-init dynamic-component-loaded gfi-dynamic-init', () => {
  $('.survey:not(.initiated)').each((i, el) => {
    new IHKSurvey($(el));
  });
})