/**
 * arrayTreeFilter.js
 *
 * @Author: zhangce
 * @Date: 17/8/31 上午11:09
 */
import { isFunction } from './isType';

var arrayTreeFilter = function arrayTreeFilter(data, filterFn, getChildren) {
    var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};

    options.childrenKeyName = options.childrenKeyName || 'children';
    var children = data || [];
    var result = [];
    var level = 0;
    var filterCallBack = function filterCallBack(item) {
        return filterFn(item, level);
    };
    var getFilterItem = function getFilterItem(children) {
        var foundItem = children.filter(filterCallBack)[0];
        if (!foundItem) {
            return false;
        } else {
            var _children = (isFunction(getChildren) ? getChildren(foundItem) : foundItem[options.childrenKeyName]) || [];
            result.push(foundItem);
            level++;
            _children.length && getFilterItem(_children);
        }
    };

    getFilterItem(children);

    return result;
};

var treeToPath = function treeToPath(tree) {
    var path = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
    var currentPath = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
    var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};

    options.childrenKeyName = options.childrenKeyName || 'children';
    tree.forEach(function (item, index) {
        var children = item[options.childrenKeyName];
        if (index !== 0) {
            currentPath.pop();
        }
        currentPath.push(item);
        if (children && children.length) {
            treeToPath(item[options.childrenKeyName], path, currentPath, options);
        } else {
            path.push(currentPath.slice(0));
        }
    });
    currentPath.pop();

    return path;
};

export { arrayTreeFilter, treeToPath };