import { Component, OnInit, OnDestroy, ViewEncapsulation } from '@angular/core'
import { Subscription } from 'rxjs'
import { UserService } from '../user.service'
import { VERSION } from '../../../environments/version'
import { SasService } from '../../services/sas.service'
import { SASjsConfig } from '@sasjs/adapter'
import { EventService } from '../../services/event.service'
import { Router } from '@angular/router'
import { globals } from 'src/app/_globals'

@Component({
  selector: 'app-header-actions',
  templateUrl: './header-actions.component.html',
  styleUrls: ['./header-actions.component.scss'],
  encapsulation: ViewEncapsulation.None,
  standalone: false
})
export class HeaderActions implements OnInit, OnDestroy {
  public userName: string = 'Not logged in'
  private reqSub: Subscription = new Subscription()
  private userSub: Subscription = new Subscription()

  public appLogs: Array<any> = []
  public debugLogs: Array<any> = []
  public failedReqs: Array<any> = []
  public sasErrors: Array<any> = []

  public isViya: boolean = false
  public sasjsConfig: SASjsConfig = new SASjsConfig()
  public requestsCount: number = 0
  public commitVer: string = ''
  public darkMode = this.eventService.darkMode

  constructor(
    private userService: UserService,
    private sasService: SasService,
    private eventService: EventService,
    public router: Router
  ) {}

  ngOnInit(): void {
    this.userSub = this.userService.userChange.subscribe((user) => {
      this.userName = user.username
    })

    this.sasjsConfig = this.sasService.getSasjsConfig()
    if (this.sasjsConfig.serverType === 'SASVIYA') {
      this.isViya = true
    }
    this.commitVer = (VERSION.tag || '').replace('v', '') + '.' + VERSION.hash
  }

  ngOnDestroy(): void {
    this.reqSub.unsubscribe()
    this.userSub.unsubscribe()
  }

  toggleDarkMode(value: boolean) {
    this.eventService.toggleDarkMode(value)
  }

  openRequestsModal() {
    this.eventService.openRequestsModal()
  }

  onDebugModeChange(dropdownItem?: any): void {
    if (this.sasjsConfig) {
      this.sasService.setDebugState(this.sasjsConfig.debug)
    }
  }

  public onDebugRowClick(evt: Event, dropdownToggle: any): void {
    evt.stopPropagation()

    if (globals.userDropdownConfig.closeOnDebugClick) {
      setTimeout(() => {
        dropdownToggle.click()
      }, 300)
    }
  }

  public logout(evt: any): void {
    evt.preventDefault()

    try {
      this.sasService.logout()
    } catch (err) {
      // TODO: handle error - show something to user
      console.error(err)
    }
  }

  public getPictureUrl() {
    return `${this.sasjsConfig.serverUrl}/identities/users/${this.userName}/avatar/content`
  }

  get isDeployPage() {
    return this.router.url.includes('deploy')
  }
}
