/*
 * Copyright (c) 2016 VMware, Inc. All Rights Reserved.
 * This software is released under MIT license.
 * The full license information can be found in LICENSE in the root directory of this project.
 */
import { Component, AfterContentInit, ViewEncapsulation } from '@angular/core'
import { Router } from '@angular/router'
import { ActivatedRoute } from '@angular/router'
import { globals } from '../_globals'
import { HelperService } from '../services/helper.service'
import { EventService } from '../services/event.service'
import { SasService } from '../services/sas.service'
import { LicenceService } from '../services/licence.service'

@Component({
  selector: 'home-component',
  styleUrls: ['./home.component.scss'],
  templateUrl: './home.component.html',
  host: {
    class: 'content-container'
  },
  encapsulation: ViewEncapsulation.None,
  standalone: false
})
export class HomeComponent implements AfterContentInit {
  public treeNodeLibraries: Array<any> | null = null
  public librariesSearch: string = ''
  public libraries: Array<String> | undefined
  public libsAndTables: Array<any> | undefined
  public tables: Array<String> | undefined
  public lib: any = ''
  public table: any = ''
  public libds: string | undefined
  public libTab: string | undefined

  public encoding: any = 'UTF-8'
  public loading: boolean = true

  public licenceState = this.licenceService.licenceState

  constructor(
    private route: Router,
    private router: ActivatedRoute,
    private licenceService: LicenceService,
    private helperService: HelperService,
    private eventService: EventService,
    private sasService: SasService
  ) {}

  public collapseLibraryItems(libraries: any, libraryToSkip: any) {
    libraries.forEach((library: any) => {
      if (library.LIBRARYID !== libraryToSkip.LIBRARYID) {
        library['expanded'] = false
      }
    })
  }

  public treeNodeClicked(event: any, library: any) {
    if (event.target.title === 'Collapse') {
      this.collapseLibraryItems(this.libraries, library)
    }
  }

  public libraryOnClick(lib: string, library: any) {
    library['expanded'] = !library['expanded']

    if (library['expanded'] && !this.table) {
      this.selectLibrary(lib, false, library)
    }

    this.collapseLibraryItems(this.libraries, library)
  }

  public selectLibrary(libs: any, initial?: boolean, library?: any) {
    library['loadingTables'] = true

    let newarray: Array<any>
    let dups: Array<any> = []
    if (this.libsAndTables) {
      newarray = this.libsAndTables[libs]
      this.table = undefined
      if (libs !== 'Please select library') {
        let arr = newarray.filter(function (el) {
          if (dups.indexOf(el) === -1) {
            dups.push(el)
            return true
          }
          return false
        })

        this.tables = arr
        globals.editor.libraries = this.libraries
      }
    }
    globals.editor.library = libs
    if (!initial) {
      this.clearGlobalsFilter()
    }

    library['loadingTables'] = false
    library['expanded'] = true
  }

  public async selectTable(ev: string, initial?: boolean) {
    let libTab = this.lib + '.' + this.table
    this.libTab = libTab
    let sasjsConfig = this.sasService.getSasjsConfig()
    let storage = sasjsConfig.serverUrl
    let metaData = sasjsConfig.appLoc
    let path =
      sasjsConfig.serverType === 'SAS9'
        ? sasjsConfig.pathSAS9
        : sasjsConfig.pathSASViya

    globals.editor.table = ev
    if (!initial) {
      this.clearGlobalsFilter()
    }
  }

  private clearGlobalsFilter() {
    globals.editor.filter.libds = ''
    globals.editor.filter.whereClause = ''
    globals.editor.filter.groupLogic = ''
    globals.editor.filter.clauses = []
    globals.editor.filter.vals = []
    globals.editor.filter.cols = []
  }

  public libTabActive(library: string, table: string) {
    if (!this.lib || !this.table) {
      return false
    }

    return library === this.lib && table === this.table
  }

  public treeOnFilter(array: any, arrToFilter: string) {
    this.helperService.treeOnFilter(array, arrToFilter)
  }

  public libraryOnFilter() {
    this.helperService.libraryOnFilter(
      this.treeNodeLibraries,
      this.librariesSearch,
      'LIBRARYREF'
    )

    globals.lineage.librariesSearch = this.librariesSearch
  }

  public onTableClick(libTable: any, library: any) {
    this.table = libTable
    this.lib = library.LIBRARYREF
    this.selectTable(libTable)
    this.editTable()
  }

  public editTable() {
    let libMem: string = this.lib + '.' + this.table
    this.route.navigateByUrl('/editor/' + libMem)
  }

  private getLibraryTableState() {
    if (globals.editor.treeNodeLibraries !== null) {
      this.treeNodeLibraries = globals.editor.treeNodeLibraries
    }

    if (globals.editor.library !== '') {
      this.lib = globals.editor.library

      let treeNodeLibrary = null
      if (this.treeNodeLibraries) {
        treeNodeLibrary = this.treeNodeLibraries.find(
          (lib: any) => lib.LIBRARYREF === this.lib
        )
      }

      this.selectLibrary(globals.editor.library, true, treeNodeLibrary)
    }
  }

  public getFromGlobals() {
    this.libsAndTables = globals.editor.libsAndTables
    this.libraries = globals.editor.libraries

    this.getLibraryTableState()

    this.loading = false
  }

  ngAfterContentInit(): void {
    if (globals.editor.startupSet) {
      this.getFromGlobals()
    } else {
      this.eventService.onStartupDataLoaded.subscribe(() => {
        this.getFromGlobals()
      })
    }
  }
}
