import {
  Component,
  OnInit,
  ChangeDetectorRef,
  ViewEncapsulation
} from '@angular/core'
import { SasStoreService } from '../../services/sas-store.service'
import { Router } from '@angular/router'
import { SasService } from '../../services/sas.service'
import { EventService } from '../../services/event.service'
import { ClrDatagridStringFilterInterface } from '@clr/angular'

interface ApproveData {
  tableId: string
  submitter: string
  baseTable: string
  submitted: string
  submitReason: string
  approver: string
  rejectLoading?: boolean
}

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

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

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

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

@Component({
  selector: 'app-approve',
  templateUrl: './approve.component.html',
  styleUrls: ['./approve.component.scss'],
  host: {
    class: 'content-container'
  },
  encapsulation: ViewEncapsulation.None,
  standalone: false
})
export class ApproveComponent implements OnInit {
  public approveList: Array<ApproveData> | undefined
  public remained: any
  public tableId: any
  public loaded: boolean = false
  public itemsNum: number = 10

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

  constructor(
    private sasStoreService: SasStoreService,
    private eventService: EventService,
    private route: Router,
    private sasService: SasService,
    private cdr: ChangeDetectorRef
  ) {}

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

  public getClicked(ind: any) {
    if (this.approveList !== undefined) {
      this.tableId = this.approveList[ind].tableId
      this.route.navigateByUrl(
        'review/approveDet/' + this.approveList[ind].tableId
      )
    }
  }

  public async rejecting(ind: any) {
    if (this.approveList !== undefined) {
      this.tableId = this.approveList[ind].tableId
    }
    let rejParams = {
      STP_ACTION: 'REJECT_TABLE',
      TABLE: this.tableId,
      STP_REASON: 'quick rejection'
    }
    try {
      ;(this.approveList || [])[ind].rejectLoading = true

      let res = await this.sasStoreService.rejecting(
        rejParams,
        'BrowserParams',
        'approvers/rejection'
      )

      if (res.fromsas[0].RESPONSE.includes('SUCCESS')) {
        ;(this.approveList || [])[ind].rejectLoading = false
        this.approveList?.splice(ind, 1)
        this.remained--
        this.cdr.detectChanges()
      }
    } catch (error) {
      this.eventService.catchResponseError('approvers/rejection', error)
    }
  }

  async ngOnInit() {
    this.fetchApprovals()
  }

  private async fetchApprovals() {
    this.itemsNum = 10
    let myJsParams: any = {}
    myJsParams.STP_ACTION = 'OPEN_APPROVALS'

    try {
      let res = await this.sasStoreService.getApprovals(
        myJsParams,
        'BrowserParams',
        'approvers/getapprovals'
      )

      this.remained = res.fromsas.length
      let approveList: ApproveData[] = res.fromsas.map(function (item: any) {
        return {
          tableId: item.TABLE_ID,
          submitter: item.SUBMITTED_BY_NM,
          submitted: item.SUBMITTED_ON_DTTM,
          baseTable: item.BASE_TABLE,
          submitReason: item.SUBMITTED_REASON_TXT
        }
      })
      this.approveList = approveList
      this.loaded = true
    } catch (error) {
      this.eventService.catchResponseError('approvers/getapprovals', error)
    }
  }

  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)
  }
}
