import { Component, OnInit, ViewChild,
    ChangeDetectorRef, ChangeDetectionStrategy } from '@angular/core';

import { MatSnackBar } from '@angular/material/snack-bar'
import { MatPaginator } from '@angular/material/paginator'
import { MatSort } from '@angular/material/sort'
import { MatTableDataSource } from '@angular/material/table'

import { AdminManageDataService, IntegrityReport, IntegrityCheck } from '../data.service'

@Component({
    selector: 'gisaf-admin-integrity',
    templateUrl: './integrity.component.html',
    styleUrls: ['./integrity.component.css'],
    changeDetection: ChangeDetectionStrategy.OnPush,
})
export class AdminIntegrityComponent implements OnInit {
    integrityChecks: IntegrityCheck[] = []
    report: IntegrityReport
    pleaseWait: boolean = false
    filterText: string
    dataSource: MatTableDataSource<object>
    @ViewChild(MatPaginator, {static: true}) paginator: MatPaginator
    @ViewChild(MatSort, {static: true}) sort: MatSort

    constructor(
        public adminManageDataService: AdminManageDataService,
        private snackBar: MatSnackBar,
        private cdr: ChangeDetectorRef,
    ) { }

    ngOnInit(): void {
        this.adminManageDataService.getIntegrityChecks().subscribe(
            resp => {
                this.integrityChecks = resp
                this.cdr.markForCheck()
            }
        )
    }

    get fieldNames(): string[] {
        return this.report && this.report.df ? this.report.df.fieldNames : []
    }

    runIntegrityCheck(integrityCheck: IntegrityCheck) {
        this.pleaseWait = true
        this.adminManageDataService.runIntegrityCheck(integrityCheck).subscribe(
            (report: IntegrityReport) => {
                this.pleaseWait = false
                this.snackBar.open(
                    `Integrity check ${integrityCheck.name} executed`,
                    'Close',
                    { duration: 3000 }
                )
                this.report = report
                this.dataSource = new MatTableDataSource(report.df ? report.df.rows : [])
                this.dataSource.sort = this.sort
                this.dataSource.paginator = this.paginator
                this.cdr.markForCheck()
            }
        )
    }

    applyFilter() {
        this.dataSource.filter = this.filterText.trim().toLowerCase()
    }
}
