import { Pipe, PipeTransform } from '@angular/core';
import { NcMenu, NgCortexService } from '@ng-cortex/core';

@Pipe({
  name: 'ncMenuFormat'
})
export class NcMenuFormatPipe implements PipeTransform {

  constructor(private _ncSrv: NgCortexService) { }

  transform(menus: NcMenu[]) {
    const result = [];
    const menuObj = {};
    menus.forEach(menu => {
      const selfMenu = menuObj[menu.id] = menuObj[menu.id] || {};
      selfMenu.icon = menu.icon;
      selfMenu.name = menu.name;
      if (menu.moduleId) {
        selfMenu.type = `item`;
        selfMenu.route = `/${this._ncSrv.activeApp.code}${menu.moduleRoute}`;
      } else {
        selfMenu.type = `folder`;
        selfMenu.unfolded = false;
        selfMenu.children = selfMenu.children || [];
      }
      if (menu.parentId) {
        const parentMenu = menuObj[menu.parentId] = menuObj[menu.parentId] || { children: [] };
        parentMenu.children.push(selfMenu);
      } else {
        result.push(selfMenu);
      }
    });
    return result;
  }

}
