import {
    MENUS
} from './menus';

export class MenuService {

    // menus;

    constructor() {
        this.menus = MENUS;
    }

    getMenus(usecases, _menus = this.menus) {
        let menus = JSON.parse(_menus);

        let unSelected = this._getUnPermissionUsecases(menus, usecases);
        for (let i = 0; i < unSelected.length; i++) {
            this._filterMenus(menus, unSelected[i]);
        }

        return menus;
    }

    _filterMenus(nodes, delId) {
        if (!nodes) {
            return [];
        }

        if (nodes.find(f => f.id === delId)) {
            nodes.splice(nodes.findIndex(v => v.id === delId), 1);
        } else {
            for (let i = 0; i < nodes.length; i++) {
                if (nodes[i].children && nodes[i].children.length > 0) {
                    this._filterMenus(nodes[i].children, delId);
                }
            }
        }
    }

    _getUnPermissionUsecases(nodes, ids) {
        let unSelectedIds = [];
        nodes.forEach(rootNode => {
            let queue = [];
            queue.push(rootNode);

            while (queue.length > 0) {
                let nodeObj = queue.shift();

                if (ids.indexOf(nodeObj.id) === -1) {
                    unSelectedIds.push(nodeObj.id);
                }

                if (nodeObj && nodeObj.children) {
                    nodeObj.children.forEach(element => {
                        queue.push(element);
                    });
                }
            }
        });

        return unSelectedIds;
    }
}