const $ = require('jquery');
class Survey{
  constructor(section) {
    this.section = section.addClass('initiated');
    this.form = section.find('form');

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

  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() {
    const heightDiff = this.section.outerHeight() - this.form.outerHeight();
    const parent = this.form.parent();
    parent.css({'height': parent.outerHeight() + 'px', 'min-height': parent.outerHeight() + 'px'});

    const posting = $.post(this.form.attr('action'), this.form.serialize()).done((result) => {
      this.result = $(result).appendTo(parent);
      parent.css('height', (this.result.outerHeight() + heightDiff) + 'px');
      this.animateResult();

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

      setTimeout(() => {
        parent.css({'height': 'auto'});
      },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)
  }
}


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