import {
  Component,
  OnInit,
  HostListener,
  ViewChild,
  ElementRef,
  EventEmitter,
  Output,
  ViewEncapsulation
} from '@angular/core'
import { Router } from '@angular/router'
import { EventService } from '../../services/event.service'
import { SasService } from '../../services/sas.service'
import { SASjsConfig } from '@sasjs/adapter'
import { globals } from '../../_globals'

@Component({
  selector: 'app-sidebar',
  templateUrl: './sidebar.component.html',
  styleUrls: ['./sidebar.component.scss'],
  encapsulation: ViewEncapsulation.None,
  standalone: false
})
export class SidebarComponent implements OnInit {
  @ViewChild('sidebarNav') sidebarNav!: ElementRef

  @Output() scrolledToBottom: EventEmitter<any> = new EventEmitter<any>()

  public sidebarOpen: boolean = true
  public sidebarWidth: number | null = null
  public sidebarMaxWidth: number | null = null
  public resizing: boolean = false
  public sasjsConfig: SASjsConfig = new SASjsConfig()
  public serverType: string

  constructor(
    private _router: Router,
    private eventService: EventService,
    private _sasService: SasService
  ) {
    this.sasjsConfig = this._sasService.getSasjsConfig()
    this.serverType = this._sasService.getServerType()
  }

  ngOnInit() {
    this.eventService.onSidebarToggle.subscribe((res: any) => {
      if (res) {
        this.sidebarOpen = res['open']
      } else {
        this.sidebarOpen = !this.sidebarOpen
      }

      this.eventService.dispatchEvent('resize')
    })
  }

  public onTreeScroll(event: any) {
    let element = event.target

    if (element.scrollTop >= element.scrollHeight - element.offsetHeight - 10) {
      this.scrolledToBottom.emit()
    }
  }

  public isMainRoute(route: string): boolean {
    return this._router.url.includes(route)
  }

  public getSubPage() {
    let url = this._router.url.split('/')

    return url[2]
  }

  public navigateToViewer() {
    globals.viewer.currentSelection = ''
    this._router.navigateByUrl('/view/data')
  }

  public resizeStart() {
    this.resizing = true

    document.body.classList.add('select-none')
  }

  public resizeEnd() {
    this.resizing = false

    document.body.classList.remove('select-none')
  }

  @HostListener('document:mousemove', ['$event'])
  onMouseMove(e: any) {
    if (this.resizing) {
      this.sidebarWidth = e.clientX

      let sidebarNavigationEl = document.getElementsByClassName('nav-tree')[0]

      if (this.sidebarWidth) {
        if (this.isOverflown(sidebarNavigationEl)) {
          this.sidebarMaxWidth =
            this.sidebarWidth >= 375
              ? this.sidebarWidth + 10
              : this.sidebarMaxWidth
        }
      }
    }
  }

  @HostListener('document:mouseup', ['$event'])
  onMouseUp(e: any) {
    if (this.resizing) {
      this.resizeEnd()
    }
  }

  isOverflown(element: any) {
    return element.scrollWidth > element.clientWidth
  }
}
