/**
 * infiniteLoader.js
 *
 * @Author: apple
 * @Date: 2018/4/12 01:34
 */

/**
 * infiniteLoader.js
 * 加载prev（存在）、当前、next（存在）三块元素
 * 1. 初始加载current元素，
 * 2. 检测当前滚动位置距离底部和顶部的距离
 *      1. 当检测到当前滚动位置与底部的位置小于设定高度时候，加载当前和next元素，将next元素推入队列，如果存在prev元素，则将prev元素推出队列。
 *      2. 当检测到当前滚动位置与顶部的位置小于设定高度时候，加载当前和next元素，将prev元素推入队列，如果存在next元素，则将next元素推出队列。
 *
 */

var initData = function initData(list) {
    var count = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 10;

    var len = list.length;
    var renderDataList = [];
    var initDataList = {
        index: 0,
        list: [],
        state: 'prev'
    };
    if (len < count) {
        renderDataList[0] = list;
        initDataList.list[0] = list;
    } else {
        var blockCount = len / count;
        if (len % count !== 0) {
            blockCount++;
        }

        var _loop = function _loop(i) {
            renderDataList[i] = [];
            renderDataList[i].push(list.filter(function (item, index) {
                return index >= count * i && index < count * i + count;
            }));
        };

        for (var i = 0; i < blockCount; i++) {
            _loop(i);
        }
        initDataList.list = renderDataList[0];
    }
    return { renderDataList: renderDataList, initDataList: initDataList };
};

var infiniteLoader = function infiniteLoader(container, space, renderList, currentDataList) {
    var clientHeight = container.clientHeight,
        scrollTop = container.scrollTop,
        scrollHeight = container.scrollHeight;

    var index = currentDataList.index;
    if (index >= 0 && index <= renderList.length) {
        if (clientHeight + space + scrollTop > scrollHeight) {
            currentDataList.index += 1;
            currentDataList.list.push(renderList[currentDataList.index][0]);
            if (currentDataList.length !== 2) {
                currentDataList.list.splice(0, 1);
            }
            currentDataList.state = 'next';
        } else if (scrollTop < space && currentDataList.index !== 0) {
            currentDataList.state = 'prev';
            currentDataList.index -= 1;
            currentDataList.list.pop();
            currentDataList.splice(0, 0, renderList[currentDataList.index - 1][0]);
        } else {
            currentDataList.state = 'current';
        }
    }
    return currentDataList;
};

export { initData, infiniteLoader };