import { Component } from '@angular/core';
import { FlatTreeControl } from '@angular/cdk/tree';
import {
  MatTreeFlattener,
  MatTreeFlatDataSource
} from '@angular/material/tree';

interface NavigationNode {
  name: string;
  children?: NavigationNode[];
}

interface NavigationFlatNode {
  expandable: boolean;
  name: string;
  level: number;
}

const TREE_DATA: NavigationNode[] = [
  {
    name: 'Fruit',
    children: [{ name: 'Apple' }, { name: 'Banana' }, { name: 'Fruit loops' }]
  },
  {
    name: 'Vegetables',
    children: [
      {
        name: 'Green'
      },
      {
        name: 'Orange'
      }
    ]
  }
];

@Component({
  selector: 'app-layouts-default',
  templateUrl: './default.layout.component.html',
  styleUrls: ['./default.layout.component.scss']
})
export class DefaultLayoutComponent {
  treeControl: FlatTreeControl<NavigationFlatNode>;
  treeFlattener: MatTreeFlattener<NavigationNode, NavigationFlatNode>;
  dataSource: MatTreeFlatDataSource<NavigationNode, NavigationFlatNode>;

  constructor() {
    this.treeControl = new FlatTreeControl<NavigationFlatNode>(
      node => node.level,
      node => node.expandable
    );

    this.treeFlattener = new MatTreeFlattener<
      NavigationNode,
      NavigationFlatNode
    >(
      (node: NavigationNode, level: number) => {
        return {
          expandable: !!node.children && 0 < node.children.length,
          name: node.name,
          level
        };
      },
      node => node.level,
      node => node.expandable,
      node => node.children
    );

    this.dataSource = new MatTreeFlatDataSource(
      this.treeControl,
      this.treeFlattener
    );

    this.dataSource.data = TREE_DATA;
  }

  hasChild = (_: number, node: NavigationFlatNode) => node.expandable;
}
