import TyComponent from '../common/component'

TyComponent({
    source: true,
    relations: {
        '../ht-sidebar-item/index': {
            type: 'descendant',
            linked(target) {
                this.children.push(target);
                target.parent = this;
                this.setActive(this.data.activeKey);
            },
            unlinked() {
                this.setActive(this.data.activeKey);
            }
        }
    },
    properties: {
        activeKey: {
            type: Number,
            value: 0,
            observer: 'setActive'
        }
    },
    created() {
        this.children = [];
    },
    methods: {
        setActive(activeKey) {
            const {
                children,
                currentActive
            } = this;
            if (!children.length) {
                return Promise.resolve();
            }
            this.currentActive = activeKey;
            const stack = [];
            if (currentActive !== activeKey && children[currentActive]) {
                stack.push(children[currentActive].setActive(false));
            }
            if (children[activeKey]) {
                stack.push(children[activeKey].setActive(true));
            }
            return Promise.all(stack);
        }
    }
});
