import { Component, OnInit } from '@angular/core'
import { SasStoreService } from '../services/sas-store.service'
import { Router } from '@angular/router'
import { ActivatedRoute } from '@angular/router'
import { SasService } from '../services/sas.service'
import { EventService } from '../services/event.service'
import { AppService } from '../services/app.service'
import { HotTableInterface } from '../models/HotTable.interface'
import { LicenceService } from '../services/licence.service'

@Component({
  selector: 'app-stage',
  templateUrl: './stage.component.html',
  styleUrls: ['./stage.component.scss'],
  host: {
    class: 'content-container'
  }
})
export class StageComponent implements OnInit {
  public table_id: any
  public jsParams: any
  public keysArray: any
  public tableDetails: any
  public loaded: boolean = false
  public licenceState = this.licenceService.licenceState
  public hotTable: HotTableInterface = {
    data: [],
    colHeaders: [],
    columns: [],
    height: 500,
    settings: {},
    licenseKey: undefined,
    maxRows: this.licenceState.value.stage_rows_allowed || Infinity
  }

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

  public submittedTableScreen() {
    this.route.navigateByUrl('/stage/' + this.table_id)
  }

  public approveTableScreen() {
    this.route.navigateByUrl('/review/approveDet/' + this.table_id)
  }

  public viewerTableScreen() {
    this.route.navigateByUrl('/view/data/' + this.tableDetails.BASE_TABLE)
  }

  public goBack() {
    this.route.navigateByUrl('/editor/' + this.tableDetails.BASE_TABLE)
  }

  public download(id: any) {
    let sasjsConfig = this.sasService.getSasjsConfig()
    let storage = sasjsConfig.serverUrl
    let metaData = sasjsConfig.appLoc
    let path = this.sasService.getExecutionPath()
    let downUrl =
      storage +
      path +
      '/?_program=' +
      metaData +
      '/services/auditors/getauditfile&table=' +
      id
    window.open(downUrl)
  }

  async ngOnInit() {
    this.licenceService.hot_license_key.subscribe(
      (hot_license_key: string | undefined) => {
        this.hotTable.licenseKey = hot_license_key
      }
    )

    if (typeof this.router.snapshot.params['tableId'] !== 'undefined') {
      this.table_id = this.router.snapshot.params['tableId']

      try {
        let res = await this.sasStoreService.getChangeInfo(this.table_id)

        if (!(res && res.jsparams))
          throw new Error('jsparams property is missing from response.')

        this.tableDetails = res.jsparams[0]
      } catch (error: any) {
        let errorObject: any = {}

        if (!error.MESSAGE) {
          errorObject.MESSAGE = error
        } else {
          errorObject = error
        }

        this.eventService.catchResponseError(
          'public/getchangeinfo',
          errorObject
        )
      }

      try {
        let res = await this.sasStoreService.openTable(this.table_id)

        if (!(res && res.stagetable))
          throw new Error('Stagetable property is missing from response.')

        let cols = res.stagetable[0]
        let colHeaders = []
        let columns: any[] = []

        for (let key in cols) {
          if (cols) {
            colHeaders.push(key)
          }
        }

        for (let index = 0; index < colHeaders.length; index++) {
          columns.push({
            data: colHeaders[index]
          })
        }

        let cells = function () {
          let cellProperties = { readOnly: true }
          return cellProperties
        }

        this.hotTable.data = res.stagetable
        this.hotTable.colHeaders = colHeaders
        this.hotTable.columns = columns
        this.hotTable.cells = cells

        this.loaded = true
        this.setFocus()
      } catch (error: any) {
        let errorObject: any = {}

        if (!error.MESSAGE) errorObject.MESSAGE = error

        this.eventService.catchResponseError(
          'auditors/getstagetable',
          errorObject
        )
        this.loaded = false
      }
    }
  }

  private setFocus() {
    setTimeout(() => {
      let approvalBtn: any = window.document.getElementById('approval-btn')
      if (!!approvalBtn) {
        approvalBtn.focus()
      }
    }, 200)
  }
}
