'use strict';

Object.defineProperty(exports, "__esModule", {
    value: true
});
exports.ChildrenMixin = undefined;

var _toConsumableArray2 = require('babel-runtime/helpers/toConsumableArray');

var _toConsumableArray3 = _interopRequireDefault(_toConsumableArray2);

var _defineProperty2 = require('babel-runtime/helpers/defineProperty');

var _defineProperty3 = _interopRequireDefault(_defineProperty2);

exports.ParentMixin = ParentMixin;

var _vue = require('vue');

var _vue2 = _interopRequireDefault(_vue);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }

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 _vue2['default'].extend({
        inject: (0, _defineProperty3['default'])({}, _parent, {
            'default': null
        }),

        computed: (0, _defineProperty3['default'])({
            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((0, _toConsumableArray3['default'])(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;
            }
        }
    });
}

exports.ChildrenMixin = ChildrenMixin;
function ParentMixin(parent) {
    return {
        provide: function provide() {
            return (0, _defineProperty3['default'])({}, parent, this);
        },
        data: function data() {
            return {
                children: []
            };
        }
    };
}