'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var getCalculatedPos = require('./getCalculatedPos.js');

// Вычисляет индекс слайда, чья целевая scroll-позиция ближе всего к текущему scrollLeft.
var getClosestIndex = function getClosestIndex(_ref) {
  var scrollRef = _ref.scrollRef,
    trackRef = _ref.trackRef,
    scrollAlign = _ref.scrollAlign,
    itemAttribute = _ref.itemAttribute;
  if (!scrollRef.current || !trackRef.current) {
    return 0;
  }
  var itemsCollection = trackRef.current.children;
  var items = Array.from(itemsCollection);
  if (!items.length) {
    return 0;
  }
  var currentLeft = scrollRef.current.scrollLeft;
  var closestIndex = 0;
  var closestDistance = Number.POSITIVE_INFINITY;
  var hasIndexedItems = items.some(function (item) {
    return item.hasAttribute(itemAttribute);
  });
  var itemsToProcess = hasIndexedItems ? items.filter(function (item) {
    return item.hasAttribute(itemAttribute);
  }) : items;
  for (var itemIndex = 0; itemIndex < itemsToProcess.length; itemIndex++) {
    var item = itemsToProcess[itemIndex];
    var parsedIndex = item.getAttribute(itemAttribute);
    var index = parsedIndex === null ? itemIndex : Number(parsedIndex);
    var pos = getCalculatedPos.getCalculatedPos({
      scrollRef: scrollRef,
      trackRef: trackRef,
      itemsCollection: itemsCollection,
      index: index,
      scrollAlign: scrollAlign,
      itemAttribute: itemAttribute
    });
    var distance = Math.abs(pos - currentLeft);
    if (distance < closestDistance) {
      closestDistance = distance;
      closestIndex = index;
    }
  }
  return closestIndex;
};

exports.getClosestIndex = getClosestIndex;
