import { Component, OnInit, ViewEncapsulation } from '@angular/core'

import { Router } from '@angular/router'
import { SASjsConfig } from '@sasjs/adapter'
import {
  LicenceService,
  SasStoreService,
  EventService,
  SasService
} from 'src/app/services'
import { ClrDatagridStringFilterInterface } from '@clr/angular'

interface HistoryData {
  tableId: string
  basetable: string
  status: string
  submitter: string
  submittedReason: string
  submitted: string
  reviewed: string
}

class BaseTableFilter implements ClrDatagridStringFilterInterface<HistoryData> {
  accepts(data: HistoryData, search: string): boolean {
    return data.basetable.toLowerCase().indexOf(search.toLowerCase()) >= 0
  }
}

class StatusFilter implements ClrDatagridStringFilterInterface<HistoryData> {
  accepts(data: HistoryData, search: string): boolean {
    return data.status.toLowerCase().indexOf(search.toLowerCase()) >= 0
  }
}

class SubmitterFilter implements ClrDatagridStringFilterInterface<HistoryData> {
  accepts(data: HistoryData, search: string): boolean {
    return data.submitter.toLowerCase().indexOf(search.toLowerCase()) >= 0
  }
}

class SubmitReasonFilter implements ClrDatagridStringFilterInterface<HistoryData> {
  accepts(data: HistoryData, search: string): boolean {
    return data.submittedReason.toLowerCase().indexOf(search.toLowerCase()) >= 0
  }
}

class SubmittedFilter implements ClrDatagridStringFilterInterface<HistoryData> {
  accepts(data: HistoryData, search: string): boolean {
    return data.submitted.toLowerCase().indexOf(search.toLowerCase()) >= 0
  }
}

class ReviewedFilter implements ClrDatagridStringFilterInterface<HistoryData> {
  accepts(data: HistoryData, search: string): boolean {
    return data.reviewed.toLowerCase().indexOf(search.toLowerCase()) >= 0
  }
}

@Component({
  selector: 'app-history',
  templateUrl: './history.component.html',
  styleUrls: ['./history.component.scss'],
  host: {
    class: 'content-container'
  },
  encapsulation: ViewEncapsulation.None,
  standalone: false
})
export class HistoryComponent implements OnInit {
  public history: Array<any> = []
  public tableTitles: Array<any> = []
  public historyArr: Array<any> = []
  public loaded: boolean = false
  public itemsNum: number = 10
  public openModal: boolean = false
  public noData: boolean = false
  public approveData: any = {}
  public sasjsConfig: SASjsConfig = new SASjsConfig()

  // Filter instances for datagrid accessibility
  public baseTableFilter = new BaseTableFilter()
  public statusFilter = new StatusFilter()
  public submitterFilter = new SubmitterFilter()
  public submitReasonFilter = new SubmitReasonFilter()
  public submittedFilter = new SubmittedFilter()
  public reviewedFilter = new ReviewedFilter()

  public histParams: { HIST: number; STARTROW: number; NOBS: number } = {
    HIST: 0,
    STARTROW: 1,
    NOBS: -1
  }
  public loadingMore: boolean = false

  public licenceState = this.licenceService.licenceState
  public Infinity = Infinity

  constructor(
    private licenceService: LicenceService,
    private sasStoreService: SasStoreService,
    private eventService: EventService,
    private router: Router,
    private sasService: SasService
  ) {
    this.sasjsConfig = this.sasService.getSasjsConfig()
  }

  public getTable(table_id: any) {
    this.router.navigateByUrl('/stage/' + table_id)
  }

  public getBaseTable(baseTable: any) {
    this.router.navigateByUrl('/view/data/' + baseTable)
  }

  public getEditTable(editTable: any) {
    this.router.navigateByUrl('/editor/' + editTable)
  }

  public getApprIndex(historyItem: any) {
    const historyItemIndex = this.historyArr.findIndex(
      (itm: any) => itm.TABLE_ID === historyItem.tableId
    )

    if (historyItemIndex > -1) {
      this.approveData = this.historyArr[historyItemIndex]
      this.openModal = true
    }
  }

  public get rowsLeftToLoad() {
    const rowsLeft = this.histParams.NOBS - this.history.length
    const rowsInStep = this.histParams.HIST

    if (rowsLeft <= 0) return 0
    if (rowsLeft > rowsInStep) return rowsInStep

    return rowsLeft
  }

  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 +
      '&_contextname=' +
      this.sasjsConfig.contextName
    window.open(downUrl)
  }

  async loadData() {
    let histParams = {
      STARTROW: this.histParams.HIST + this.histParams.STARTROW
    }

    this.loadingMore = true

    try {
      let res = await this.sasStoreService.getHistory(
        histParams,
        'BrowserParams',
        'approvers/gethistory'
      )

      this.loadingMore = false

      this.histParams = res.histparams[0]

      let tableTitles: Array<any>
      const fromsas = res.fromsas.slice(
        0,
        this.licenceState.value.history_rows_allowed
      )

      if (fromsas.length > 0) {
        const arr = fromsas
        this.historyArr = fromsas

        tableTitles = Object.keys(arr[0])

        this.tableTitles = tableTitles

        let historyTable = fromsas.map(function (item: any) {
          return {
            tableId: item.TABLE_ID,
            submitter: item.SUBMITTER,
            submittedReason: item.SUBMITTED_REASON_TXT,
            submitted: item.SUBMITTED,
            status: item.STATUS,
            reviewReason: item.REVIEW_REASON_TXT,
            reviewer: item.REVIEWER,
            reviewed: item.REVIEWED,
            numOfApprovals: item.NUM_OF_APPROVALS_REQUIRED,
            basetable: item.BASE_TABLE
          }
        })

        this.history.push(...historyTable)
        this.loaded = true
      } else {
        this.loaded = true

        if (this.history.length === 0) this.noData = true
      }
    } catch (error) {
      this.eventService.catchResponseError('approvers/gethistory', error)
      this.loadingMore = false
    }
  }

  async ngOnInit() {
    this.loadData()
  }
}
