import {Injectable} from '@angular/core';
import {BehaviorSubject} from "rxjs";

import { PagesService } from './pages.service';



@Injectable({providedIn: 'root'})
export class MenuService {
  constructor( 
    private pagesService: PagesService
  ){}

  public pagesTree = new BehaviorSubject({data:[]});
  public navURL:string;



  setPagesTree(pageURL?:any){
    let include = {include: 'hasChildren, children.hasChildren'};
    if (pageURL){
      this.pagesService.find(pageURL,include).subscribe(        
        res => {
          this.pagesTree.next({data:[res.data]})
        }
      )
    }else{
      this.pagesService.root(include).subscribe(
        res => {
          this.pagesTree.next(res)
        }
      );
    }
  }

  findChildren(item){
    let include = {include: 'hasChildren, children.hasChildren'};
    if (!item.children && item.hasChildren) this.pagesService.find(item.link,include).subscribe(
      res=>{
        item.children = res.data.children
      }
    )
  }

}