import {
  Component,
  AfterViewInit,
  OnInit,
  ViewEncapsulation
} from '@angular/core'
import { Subscription } from 'rxjs'
import { ActivatedRoute, Router } from '@angular/router'
import { SasStoreService, EventService, SasService } from '../../services'
import { ClrDatagridStringFilterInterface } from '@clr/angular'

interface SubmitterData {
  tableId: string
  base: string
  submitted: string
  submitReason: string
  approver: string
}

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

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

@Component({
  selector: 'app-submitter',
  templateUrl: './submitter.component.html',
  styleUrls: ['./submitter.component.scss'],
  host: {
    class: 'content-container'
  },
  encapsulation: ViewEncapsulation.None,
  standalone: false
})
export class SubmitterComponent implements OnInit, AfterViewInit {
  public remained: number = 0
  public itemsNum!: number
  public submitterList!: SubmitterData[]
  public loaded: boolean = false
  public subReady: boolean = false
  public detailsOpen: boolean = false
  public submitter!: string
  public submitData!: Array<any>
  private _readySub!: Subscription
  private _backToSub!: Subscription

  // Filter instances for datagrid accessibility
  public submittedFilter = new SubmittedFilter()
  public submitReasonFilter = new SubmitReasonFilter()

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

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

  public goToDetails(table_id: any) {
    this.router.navigateByUrl('/review/submitted/' + table_id)
  }

  public getDetails(sub: any, index: any) {
    this.subReady = true
    setTimeout(() => {
      this.sasStoreService.sendDetails(sub, index, this.submitData)
    }, 0)
  }

  async ngOnInit() {
    const tableIdParam = this.route.snapshot.params['tableId']

    this.itemsNum = 10
    try {
      let res = await this.sasStoreService.getSubmitts()

      this.remained = res.fromsas.length
      if (this.remained > 0) {
        this.submitter = res.fromsas[0].SUBMITTED_BY_NM
        let submitterList: SubmitterData[] = res.fromsas.map(function (
          item: any
        ) {
          return {
            tableId: item.TABLE_ID,
            base: item.BASE_TABLE,
            submitted: item.SUBMITTED_ON_DTTM,
            submitter: item.SUBMITTED_BY_NM,
            submitReason: item.SUBMITTED_REASON_TXT
          }
        })
        this.submitterList = submitterList
        this.submitData = res.fromsas

        // Details page
        if (typeof tableIdParam !== 'undefined') {
          const submitterIndex = this.submitterList.findIndex(
            (x) => x.tableId === tableIdParam
          )

          if (submitterIndex > -1) {
            const submitter = this.submitterList[submitterIndex]

            this.getDetails(submitter, submitterIndex)
          }
        }
      }
      this.loaded = true
    } catch (error) {
      this.eventService.catchResponseError('editors/getsubmits', error)
    }
  }

  ngAfterViewInit() {
    this._readySub = this.sasStoreService.setSubmit.subscribe((sub) => {
      this.subReady = sub
    })

    this._backToSub = this.sasStoreService.setSubmitList.subscribe((sub) => {
      this.subReady = !this.subReady
      this.detailsOpen = false
    })
  }

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