import { Component, OnInit, ViewEncapsulation } from '@angular/core'
import moment from 'moment'
import { VERSION } from 'src/environments/version'
import { LicenseKeyData } from '../models/LicenseKeyData'
import { AppService } from '../services/app.service'
import { LicenceService } from '../services/licence.service'
import { SasService } from '../services/sas.service'
import { AppInfo } from './models/app-info.model'
import { EnvironmentInfo } from './models/environment-info.model'
import { AppSettingsService } from '../services/app-settings.service'
import { AppSettings } from '../models/AppSettings'
import { RequestWrapperResponse } from '../models/request-wrapper/RequestWrapperResponse'
import { globals } from '../_globals'

@Component({
  selector: 'app-system',
  templateUrl: './system.component.html',
  styleUrls: ['./system.component.scss'],
  host: {
    class: 'content-container'
  },
  encapsulation: ViewEncapsulation.None,
  standalone: false
})
export class SystemComponent implements OnInit {
  appInfo: AppInfo = {
    adapterVersion: VERSION.adapterVersion || 'n/a',
    appVersion: (VERSION.tag || '').replace('v', ''),
    buildTimestamp: moment(parseInt(VERSION.timestamp)).format(
      'DD-MMM-YYYY HH:MM'
    )
  }
  serverType: string
  environmentInfo: EnvironmentInfo | null
  licenceInfo: LicenseKeyData | null
  http: boolean = location.protocol === 'http:'
  refreshingDataCatalog: boolean = false
  refreshingDataLineage: boolean = false
  response: string = 'No response'
  responseModal: boolean = false

  Infinity = Infinity
  dcLib: string = globals.dcLib
  targetLibref: string = globals.dcLib

  licenceState = this.licenceService.licenceState
  settings: AppSettings

  constructor(
    private appService: AppService,
    private sasService: SasService,
    private licenceService: LicenceService,
    private appSettingsService: AppSettingsService
  ) {
    this.serverType = this.sasService.getServerType()
    this.licenceInfo = this.licenceService.getLicenseKeyData()
    this.environmentInfo = this.appService.getEnvironmentInfo()
    this.settings = this.appSettingsService.settings.value

    if (this.environmentInfo.AUTOEXEC) {
      this.environmentInfo.AUTOEXEC = decodeURIComponent(
        this.environmentInfo.AUTOEXEC
      )
    }

    this.appSettingsService.settings.subscribe((settings: AppSettings) => {
      this.settings = settings
    })
  }

  ngOnInit(): void {}

  settingChange(event: Event) {
    this.appSettingsService.setAppSettings(this.settings)
  }

  isValidLibref(value: string): boolean {
    return /^[A-Za-z_]\w{0,7}$/.test(value.trim())
  }

  downloadConfiguration() {
    let sasjsConfig = this.sasService.getSasjsConfig()
    let storage = sasjsConfig.serverUrl
    let metaData = sasjsConfig.appLoc
    let path = this.sasService.getExecutionPath()
    let lib = this.targetLibref.toUpperCase().trim()
    let downUrl =
      storage + path + '/?_program=' + metaData + '/services/admin/exportconfig'
    if (lib && lib !== this.dcLib && this.isValidLibref(lib)) {
      downUrl += '&dclib=' + encodeURIComponent(lib)
    }
    window.open(downUrl)
  }

  refreshDataCatalog() {
    this.refreshingDataCatalog = true

    this.sasService
      .request('admin/refreshcatalog', null)
      .then((res: RequestWrapperResponse) => {
        this.response = this.parseResponse(res.adapterResponse)
        this.responseModal = true
      })
      .catch((err: any) => {
        this.response = this.parseResponse(err.adapterResponse)
        this.responseModal = true
      })
      .finally(() => {
        this.refreshingDataCatalog = false
      })
  }

  refreshDataLineage() {
    this.refreshingDataLineage = true

    this.sasService
      .request('admin/refreshtablelineage', null)
      .then((res: RequestWrapperResponse) => {
        this.response = this.parseResponse(res.adapterResponse)
        this.responseModal = true
      })
      .catch((err: any) => {
        this.response = this.parseResponse(err.adapterResponse)
        this.responseModal = true
      })
      .finally(() => {
        this.refreshingDataLineage = false
      })
  }

  private parseResponse(res: any) {
    return typeof res === 'object' ? JSON.stringify(res) : res
  }
}
