import { Component, OnInit } from '@angular/core';
import { NgCortexService, NcApp } from '@ng-cortex/core';

@Component({
  selector: 'nc-app-list',
  templateUrl: './nc-app-list.component.html',
  styleUrls: ['./nc-app-list.component.scss']
})
export class NcAppListComponent implements OnInit {

  _appGroups = [];
  _appKeyword: string = null;

  constructor(private _ncSrv: NgCortexService) { }

  ngOnInit() {
    this._generateAppGroups(this._ncSrv.apps);
  }

  _searchApps(keyword: string) {
    if (keyword) {
      const keywordReg = new RegExp(keyword, `i`);
      this._generateAppGroups(
        this._ncSrv.apps.filter(app => {
          return keywordReg.test(app.name) || keywordReg.test(app.code);
        })
      );
    } else {
      this._generateAppGroups(this._ncSrv.apps);
    }
  }

  private _generateAppGroups(apps: NcApp[]) {
    const groupObj = {};
    apps.forEach(app => {
      const name = app.groupName || `其它`;
      groupObj[name] = groupObj[name] || [];
      groupObj[name].push(app);
    });
    this._appGroups = Object.keys(groupObj)
      .map(name => {
        return {
          name: name,
          children: groupObj[name]
        };
      });
  }

}
