import {Component, OnInit, ChangeDetectionStrategy, Input, ChangeDetectorRef} from '@angular/core';
import {tap} from 'rxjs/operators';
import {BaseList} from 'src/app/core/base/base-list';
import {TestingScoreService} from 'src/app/core/service/card-print/testing-score.service';
import {ExamResultPrintService} from 'src/app/core/service/report/exam-result-print/exam-result-print.service';
import {createQueryStringFromObject} from 'src/app/shared/util/func';
import {formatDate} from "@angular/common";

@Component({
    selector: 'app-search',
    templateUrl: './search.component.html',
    styleUrls: ['./search.component.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class SearchComponent extends BaseList implements OnInit {
    query = {
        academic_year_code: null,
        academic_semester_code: null,
        student_code: null,
        test_date: null,
        period: null,
    }
    result: any = [];
    @Input() academicYearList: any = [];
    @Input() academicSemList: any = [];

    constructor(
        private testingScoreSV: TestingScoreService,
        private cdr: ChangeDetectorRef,
        private resultSV: ExamResultPrintService
    ) {
        super()
    }

    ngOnInit(): void {
    }

    print(x) {
        const fileURL = this.resultSV.print(x.tests_uid)
        window.open(fileURL)
    }

    onSearch() {
        if (this.query.test_date !== null) {
            this.query.test_date = formatDate(this.query.test_date, 'yyyy-MM-dd', 'en-US')
        }
        const query = createQueryStringFromObject(this.query);
        this.testingScoreSV.search('?' + query).pipe(
            tap(x => this.result = this.updateMatTable(x)),
            tap(x => this.cdr.detectChanges())
        ).subscribe()
    }

    clear() {
        this.query = {
            academic_year_code: null,
            academic_semester_code: null,
            student_code: null,
            test_date: null,
            period: null,
        }
        this.result = this.updateMatTable([])
    }

}
