import { Component, OnInit } from '@angular/core';
import { NavService, Menu } from '../../../../services/nav.service';

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

  public menuItems!: Menu[];
  public items!: Menu[];

  public searchResult: boolean = false;
  public searchResultEmpty: boolean = false;
  public text!: string;

  constructor(public navServices: NavService) {
    this.navServices.items.subscribe(menuItems => this.items = menuItems);
  }

  ngOnInit() {
  }

  searchToggle() {
    this.navServices.search = false;
  }

  searchTerm(term: any): void {
    // Handle layout fix or removal based on the presence of a search term
    term ? this.addFix() : this.removeFix();
  
    // Return early if no term is provided
    if (!term) {
      this.menuItems = [];
      return;
    }
  
    // Initialize an array to store the search results
    const items: any[] = [];
    term = term.toLowerCase(); // Convert search term to lowercase for case-insensitive comparison
  
    // Function to recursively search items
    const search = (menuItems: any[]) => {
      menuItems.forEach((item: any) => {
        if (item?.title && item.title.toLowerCase().includes(term) && item.type === 'link') {
          items.push(item);
        }
  
        if (item.children) {
          item.children.forEach((subItem: any) => {
            if (subItem.title.toLowerCase().includes(term) && subItem.type === 'link') {
              subItem.icon = item.icon; // Assign the parent icon
              items.push(subItem);
            }
  
            if (subItem.children) {
              subItem.children.forEach((subSubItem: any) => {
                if (subSubItem.title.toLowerCase().includes(term)) {
                  subSubItem.icon = item.icon; // Assign the parent icon
                  items.push(subSubItem);
                }
              });
            }
          });
        }
      });
    };
  
    // Start searching from the top-level items
    search(this.items);
  
    // Check if search results are empty
    this.checkSearchResultEmpty(items);
  
    // Update menuItems with the search results
    this.menuItems = items;
  }

  checkSearchResultEmpty(items: string | any[]) {
    if (!items.length)
      this.searchResultEmpty = true;
    else
      this.searchResultEmpty = false;
  }

  addFix() {
    this.searchResult = true;
    document.getElementsByTagName('body')[0].classList.add('offcanvas');
  }

  removeFix() {
    this.searchResult = false;
    this.text = "";
    document.getElementsByTagName('body')[0].classList.remove('offcanvas');
  }

}
