import {
  AfterViewInit, ChangeDetectorRef,
  Component,
  ElementRef,
  Inject,
  Input, OnChanges,
  OnDestroy,
  OnInit,
  PLATFORM_ID, SimpleChanges,
  ViewChild
} from '@angular/core';
import {MenuItem} from "../../../sharedComponents/menu";
import {ActivatedRoute, NavigationEnd, Router} from "@angular/router";
import {DomSanitizer} from "@angular/platform-browser";
import {properties} from "../../../../../environments/environment";
import {LayoutService} from "./layout.service";
import {Subscription} from "rxjs";

declare var UIkit;

@Component({
  selector: 'dashboard-sidebar',
  templateUrl: 'sideBar.component.html'
})
export class SideBarComponent implements OnInit, AfterViewInit, OnDestroy, OnChanges {
  @Input() items: MenuItem[] = [];
  @Input() activeItem: string = '';
  @Input() activeSubItem: string = '';
  @Input() backItem: MenuItem = null;
  @Input() queryParamsHandling;
  @Input() logoURL: string;
  @ViewChild("nav") nav: ElementRef;
  @ViewChild("sidebar_offcanvas") sidebar_offcanvas: ElementRef;
  public offset: number;
  public properties = properties;
  private subscriptions: any[] = [];
  private init: boolean = false;
  
  constructor(private route: ActivatedRoute, private router: Router,
              private sanitizer: DomSanitizer, private layoutService: LayoutService,
              private cdr: ChangeDetectorRef, @Inject(PLATFORM_ID) private platformId) {
    this.subscriptions.push(this.router.events.subscribe(event => {
      if(event instanceof NavigationEnd && (!this.activeItem && !this.activeSubItem)) {
        this.setActiveMenuItem();
      }
    }));
  }

  ngOnInit() {
    if (typeof document !== "undefined") {
      this.offset = Number.parseInt(getComputedStyle(document.documentElement).getPropertyValue('--header-height'));
    }
    this.setActiveMenuItem();
  }

  ngAfterViewInit() {
    setTimeout(() => {
      this.toggle(true);
    });
  }

  ngOnChanges(changes: SimpleChanges) {
    if(changes.activeItem || changes.activeSubItem || changes.items) {
      this.setActiveMenuItem();
      if(this.init && changes.items) {
        this.toggle();
      }
    }
  }

  ngOnDestroy() {
    this.layoutService.setActiveSidebarItem(null);
    this.subscriptions.forEach(subscription => {
      if(subscription instanceof Subscription) {
        subscription.unsubscribe();
      }
    });
  }
  
  toggle(init: boolean = false) {
    this.init = this.init || init;
    if(this.nav && typeof UIkit !== "undefined") {
      setTimeout(() => {
        if(this.items[this.activeIndex]?.items?.length > 0) {
          UIkit.nav(this.nav.nativeElement).toggle(this.activeIndex, true);
        }
      });
    }
  }
  
  get isBrowser() {
    return this.platformId === 'browser';
  }
  
  get currentRoute() {
    return {
      route: this.router.url.split('?')[0].split('#')[0],
      fragment: this.route.snapshot.fragment
    }
  }
  
  get activeIndex(): number {
    return this.items?this.items.findIndex(item => item.isActive):0;
  }
  
  getItemRoute(item: MenuItem) {
    if(this.activeSubItem && item.items.length > 0) {
      let subItem = item.items.find(subItem => subItem._id === this.activeSubItem);
      return subItem?subItem.route:(item.route?item.route:null);
    } else {
      return item.route?item.route:null;
    }
  }

  setActiveMenuItem() {
    this.items.forEach(item => {
      item.isActive = this.isTheActiveMenuItem(item);
      if(item.isActive) {
        if(item.items.length > 0) {
          item.items.forEach(subItem => {
            subItem.isActive = this.isTheActiveMenuItem(item, subItem);
            if(subItem.isActive) {
              this.layoutService.setActiveSidebarItem({
                name: item.title,
                icon: item.icon,
                subItem: {
                  name: subItem.title
                }
              });
            }
          });
        } else {
          this.layoutService.setActiveSidebarItem({
            name: item.title,
            icon: item.icon
          });
        }
      } else {
        item.items.forEach(subItem => {
          subItem.isActive = false;
        });
      }
    });
    if(!this.items.find(item => item.isActive)) {
      this.layoutService.setActiveSidebarItem(null);
    }
    this.cdr.detectChanges();
  }
  
  private isTheActiveMenuItem(item: MenuItem, subItem: MenuItem = null): boolean {
    if (this.activeItem || this.activeSubItem) {
      return (!subItem && this.activeItem === item._id) ||
        (subItem && this.activeItem === item._id && this.activeSubItem === subItem._id);
    } else {
      if (subItem) {
        return MenuItem.isTheActiveMenu(subItem, this.currentRoute);
      }
      return MenuItem.isTheActiveMenu(item,this.currentRoute);
    }
  }
  
  public get open() {
    return this.layoutService.open;
  }
  
  public closeOffcanvas() {
    if(this.sidebar_offcanvas) {
      UIkit.offcanvas(this.sidebar_offcanvas.nativeElement).hide();
    }
  }
}
