import _toConsumableArray from 'babel-runtime/helpers/toConsumableArray';
import _defineProperty from 'babel-runtime/helpers/defineProperty';
export { ChildrenMixin };
import Vue from 'vue';

function flattenVNodes(vnodes) {
    var result = [];

    function traverse(vnodes) {
        vnodes.forEach(function (vnode) {
            result.push(vnode);

            if (vnode.children) {
                traverse(vnode.children);
            }
        });
    }

    traverse(vnodes);
    return result;
}

function ChildrenMixin(_parent) {
    var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};

    var indexKey = options.indexKey || 'index';

    return Vue.extend({
        inject: _defineProperty({}, _parent, {
            'default': null
        }),

        computed: _defineProperty({
            parent: function parent() {
                if (this.disableBindRelation) {
                    return null;
                }

                return this[_parent];
            }
        }, indexKey, function () {
            this.bindRelation();
            return this.parent.children.indexOf(this);
        }),

        mounted: function mounted() {
            this.bindRelation();
        },
        beforeDestroy: function beforeDestroy() {
            var _this = this;

            if (this.parent) {
                this.parent.children = this.parent.children.filter(function (item) {
                    return item !== _this;
                });
            }
        },


        methods: {
            bindRelation: function bindRelation() {
                if (!this.parent || this.parent.children.indexOf(this) !== -1) {
                    return;
                }

                var children = [].concat(_toConsumableArray(this.parent.children), [this]);
                var vnodes = flattenVNodes(this.parent.$slots['default']);
                children.sort(function (a, b) {
                    return vnodes.indexOf(a.$vnode) - vnodes.indexOf(b.$vnode);
                });

                this.parent.children = children;
            }
        }
    });
}

export function ParentMixin(parent) {
    return {
        provide: function provide() {
            return _defineProperty({}, parent, this);
        },
        data: function data() {
            return {
                children: []
            };
        }
    };
}