import { Component, OnInit, ViewEncapsulation } from '@angular/core'
import { SASjsConfig } from '@sasjs/adapter'
import { EventService, HelperService, SasService } from '../services'
import { SasViyaService } from '../services/sas-viya.service'
import { globals } from '../_globals'
import { Collection } from './models/collection.model'
import { Link } from './models/link.model'
import { ViyaApis } from './models/viya-apis.models'

@Component({
  selector: 'app-viya-api-explorer',
  templateUrl: './viya-api-explorer.component.html',
  styleUrls: ['./viya-api-explorer.component.scss'],
  host: {
    class: 'content-container'
  },
  encapsulation: ViewEncapsulation.None,
  standalone: false
})
export class ViyaApiExplorerComponent implements OnInit {
  collections: ViyaApis = {}
  collection: string = ''

  endpointLinks: Link[] = []
  endpointItems: any[] = []
  endpointJson: any
  endpoint: {
    url: string
    start: number | undefined
    limit: number | undefined
  } = {
    url: '',
    start: -1,
    limit: -1
  }

  endpointLoading: boolean = false
  collectionLoading: boolean = false
  rawJson: boolean = false

  linksSearch: string = ''
  itemsSearch: string = ''

  public sasjsConfig: SASjsConfig = new SASjsConfig()

  constructor(
    private helperService: HelperService,
    private sasViyaService: SasViyaService,
    private sasService: SasService,
    private eventService: EventService
  ) {}

  ngOnInit(): void {
    this.sasjsConfig = this.sasService.getSasjsConfig()
    this.collections = this.sasViyaService.getAllCollections()
  }

  linksListOnFilter() {
    this.helperService.libraryOnFilter(
      this.endpointLinks,
      this.linksSearch,
      'rel'
    )

    globals.viyaApi.linkssSearch = this.linksSearch
  }

  itemsListOnFilter() {
    this.helperService.libraryOnFilter(
      this.endpointItems,
      this.itemsSearch,
      'name'
    )

    globals.viyaApi.itemsSearch = this.itemsSearch
  }

  linkOnClick(link: Link) {
    this.loadUrl(link.href)
  }

  itemOnClick(item: any) {
    this.loadUrl(item.links[0].href)
  }

  treeNodeClicked(event: any, item: any, tree: any) {
    if (event.target.title === 'Collapse') {
      this.collapseTreeItems(tree, item)
    }
  }

  collapseTreeItems(tree: any, itemToSkip: any) {
    tree.forEach((item: any) => {
      if (JSON.stringify(item) !== JSON.stringify(itemToSkip)) {
        item['expanded'] = false
      }
    })
  }

  updateSelectedCollection() {
    globals.viyaApi.selectedCollection = this.collection
    this.endpoint.url = this.collection

    this.collectionLoading = true

    this.sasViyaService.getByCollection(this.collection).subscribe(
      (collection: Collection) => {
        this.endpointLinks = collection.links
        this.endpointItems = collection.items ? collection.items : []
        this.collectionLoading = false

        this.endpointJson = collection

        this.endpoint.start = collection.start
        this.endpoint.limit = collection.limit
      },
      (err: any) => {
        this.collectionLoading = false

        let message = 'Error occurred while sending request'

        if (err.message) message = err.message
        if (err.error) {
          if (err.error.message) message = err.error.message
          if (err.error.remediation)
            message = `${message}\n${err.error.remediation}`
        }

        this.eventService.showAbortModal(null, message, null, 'HTTP Error')
      }
    )
  }

  onJsonLinkClick(link: string) {
    this.loadUrl(link)
  }

  onJsonClick(event: any) {
    event.preventDefault()

    if (event.srcElement.tagName === 'A') {
      const url = event.srcElement.href.split(event.srcElement.host)[1]

      this.loadUrl(url)
    }
  }

  onBreadcumsClick(event: any) {
    event.preventDefault()

    if (!event.srcElement.href) return

    const url = event.srcElement.href.split(event.srcElement.host)[1]

    this.loadUrl(url)
  }

  copyJson() {
    if (this.endpointJson)
      navigator.clipboard.writeText(JSON.stringify(this.endpointJson, null, 2))
  }

  copyBreadcrums() {
    if (this.endpoint && this.endpoint.url)
      navigator.clipboard.writeText(this.endpoint.url)
  }

  applyQueryParams() {
    const start = this.endpoint.start
    const limit = this.endpoint.limit
    const params = `?${start !== undefined ? 'start=' + start : ''}${
      limit !== undefined ? '&limit=' + limit : ''
    }`

    const url = `${this.endpoint.url.split('?')[0]}${params}`
    this.loadUrl(url)
  }

  loadUrl(url: string) {
    this.endpointLoading = true

    this.sasViyaService.getByUrl(url).subscribe(
      (collection: Collection) => {
        this.endpointLinks = collection.links
        this.endpointItems = collection.items ? collection.items : []
        this.endpointJson = collection
        this.endpointLoading = false

        this.endpoint.url = url
        this.endpoint.start = collection.start
        this.endpoint.limit = collection.limit
      },
      (err: any) => {
        this.endpointLoading = false

        let message = 'Error occurred while sending request'

        if (err.message) message = err.message
        if (err.error) {
          if (err.error.message) message = err.error.message
          if (err.error.remediation)
            message = `${message}\n${err.error.remediation}`
        }

        this.eventService.showAbortModal(null, message, null, 'HTTP Error')
      }
    )
  }
}
