import { updateProductPrice } from '@assets/js/wpj.product.helpers.js';

export function initVariations(allVariations) {
   const $sizeConvertionWrapper = $('[data-variation-size-convertion-wrapper]');
   if (!allVariations) {
      return false;
   }

   if (allVariations.length) {
      let queries = {};
      $.each(document.location.search.substr(1).split('&'),function(c,q){
         const i = q.split('=');
         if (i[0] && i[1]) {
            queries[i[0].toString()] = i[1].toString();
         }
      });

      const hash = location.href.split('#')[1] || queries['id_variation'] || '';

      if (hash.length > 0 && !isNaN(parseFloat(hash)) && isFinite(hash)) {
         const $variant = allVariations.find(`[name="IDvariation"][value="${hash}"]`);

         if ($variant.length) {
            $variant.click();
         }

         checkSelectedVariation(allVariations);
      } else if (allVariations.find('input[name="IDvariation"]:checked')) {
         checkSelectedVariation(allVariations);
      }
   }

   allVariations.on('change', 'input[name="IDvariation"]', function() {
      checkSelectedVariation(allVariations);
   });

   allVariations.on('change', 'input[name^="IDLabel"]', function() {
      if ($sizeConvertionWrapper.length) {
         const labelAndValue = getLabelAndValue($(this));
         $(`[name^="IDLabel_${labelAndValue[0]}"]`).prop('checked', false);
         $(this).prop('checked', true);
      }

      checkVarFromLabels($(this));
   });
}

export function validateVariations(allVariations) {
   if (allVariations.length) {
      const selectedVariation = allVariations.find('[name="IDvariation"]:checked');
      if (!selectedVariation.length) {
         return false;
      }
   }

   return true;
}

export function checkSelectedVariation(allVariations) {
   const $selectedVariation = allVariations.find('[name="IDvariation"]:checked');
   const selectedVarId = $selectedVariation.val();
   const varData = wpj.variations[selectedVarId];

   if ($selectedVariation.length && varData) {
      $('.btn-insert [data-variation-error]').hide();

      if (!$('[data-quantity-discounts="quantityDiscounts"]').length) {
         updateProductPrice(varData.price, varData.priceNoVat, varData.priceCommon);
      }

      if (varData.bonusPoints) {
         $('[data-bonus-points]').html(varData.bonusPoints);
      }

      if (varData.ean) {
         $('[data-ean]').html(varData.ean);
      }

      if (varData.flag) {
         $('[data-flag]').html(varData.flag);
      }

      if (varData.combinations) {
         checkLabels(varData.combinations);

         const $otherLabels = $('input[name^="IDLabel"]');
         disableInvalidLabels($otherLabels, varData.combinations);
      }

      if (typeof varData.watchdog !== 'undefined' && MODULES.WATCHDOG) {
         import('@assets/js/wpj.watchdog.js').then(wpjWatchdog => {
            wpjWatchdog.updateVarWatchdog(varData, selectedVarId);
         });
      }

      $('[data-deliverytime]')
         .html(varData.deliveryTime)
         .attr('class', function(i, c) {
            return c.replace(/(^|\s)(delivery-)(-?\d+)/g, '$1$2' + varData.deliveryTimeIndex);
         });

      if (MODULES.QUANTITY_DISCOUNT) {
         import('@assets/js/wpj.quantity-discount.js').then(quantityDiscounts => {
            quantityDiscounts.reloadQuantityDiscounts($selectedVariation.val());
         });
      }

     /* if ($sizeConvertionWrapper) {
         this.selectConvertionVariation(selectedVarId);
      }*/

      $selectedVariation.trigger('variationSelected');
   }

   if (history.replaceState) {
      history.replaceState(
         null,
         null,
         typeof $selectedVariation.val() != 'undefined' ? '#' + $selectedVariation.val() : ''
      );
   }
}

function checkLabels(combinations) {
   for (const comb in combinations) {
      $(`[name^="IDLabel_${comb}"][value="${combinations[comb]}"]`).prop('checked', true);
      checkConvertionLabels(comb, combinations[comb]);
   }
}

function checkConvertionLabels(label_id, label_value) {
   const $sizeConvertionWrapper = $('[data-variation-size-convertion-wrapper]');
   if ($sizeConvertionWrapper.length) {
     // $(`[name^="IDLabel_${label_id}"]`).prop('checked', false);
      const $siblingsVariations = $sizeConvertionWrapper.find(`input[name^=IDLabel_${label_id}][value=${label_value}]`);
      $siblingsVariations.prop('checked', true);

      let selected_title = '';
      $siblingsVariations.each(function(index) {
         selected_title = selected_title + (index === 0 ? '' : '&nbsp;&nbsp;|&nbsp; ') + $(this).next('label').data('title');
      });

      $('[data-variation-size-convertion-trigger]').html(selected_title);
   }
}

/**
 * Searches through wpj.variations object for variation with given label combination
 * @param {object} combinations { id_label: value, ... }
 * @returns {(number|false)} matching variation ID
 */
function findVariation(combinations) {
   let len = Object.getOwnPropertyNames(combinations).length;
   for (const variation in wpj.variations) {
      let count = 0;

      for (const comb in combinations) {
         if (wpj.variations[variation].combinations[comb] === combinations[comb]) {
            count++;
         }
      }

      if (count === len) {
         return variation;
      }
   }
   return false;
}

/**
 * Returns label ID and value from input
 * @param {jQuery} $input - jQuery obj. input
 * @returns {number[]} ID label, ID value
 */
function getLabelAndValue($input) {
   const comb_id = $input.attr('name').split('_')[1];
   const value = parseInt($input.val());
   return [comb_id, value];
}

function disableInvalidLabels($otherLabels, combinations) {
   $otherLabels.each(function() {
      const $this = $(this);
      const labelAndValue = getLabelAndValue($this);
      const local_combination = { ...combinations };
      local_combination[labelAndValue[0]] = labelAndValue[1];

      const variation = findVariation(local_combination);
      $this.toggleClass('disabled', !variation);

      if (variation && wpj.variations[variation].hasOwnProperty('watchdog')) {
         $this.toggleClass('soldout', variation && wpj.variations[variation]['watchdog']);
      }
   });
}

function checkVarFromLabels($el) {
   const $allLabels = $el.closest('form').find('input[name^="IDLabel"]:checked');
   const combinations = {};
   let variation;

   $el.removeClass('disabled');

   $allLabels.each(function() {
      const labelAndValue = getLabelAndValue($(this));
      combinations[labelAndValue[0]] = labelAndValue[1];
   });

   var $otherLabels = $el
      .closest('form')
      .find('input[name^="IDLabel"]')
      .not('[name=' + $el.attr('name') + ']');

   variation = findVariation(combinations);
   checkLabels(combinations);

   if (variation) {
      $(`[name="IDvariation"][value="${variation}"]`).click();
   } else {
      console.log('neexistujici varianta');
      $('.btn-insert [data-variation-error]').show();
      $('[name="IDvariation"]:checked').prop('checked', false);
      $otherLabels.filter(':checked').prop('checked', false);
      disableInvalidLabels($otherLabels, combinations);
      $otherLabels
         .filter(':not(.disabled)')
         .first()
         .click();
   }
}
