import { Component, OnInit, ChangeDetectionStrategy, ChangeDetectorRef, AfterViewInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { filter, switchMap, tap } from 'rxjs/operators';
import { BaseSubList } from 'src/app/core/base/base-sub-list';
import { SweetalertService } from 'src/app/core/service/sweetalert/sweetalert';
import { GradingService } from 'src/app/core/service/testing-information/grading.service';
import { TestingInformationService } from 'src/app/core/service/testing-information/testing-information.service';

@Component({
  selector: 'app-grade-summary-subject-list',
  templateUrl: './grade-summary-subject-list.component.html',
  styleUrls: ['./grade-summary-subject-list.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class GradeSummarySubjectListComponent extends BaseSubList implements OnInit,AfterViewInit{
  column = ['0','1','2','3','4','5','6','7','8','9']
  subjectList;
  data;
  constructor(
    public activeRoute: ActivatedRoute,
    private testingInfoSV: TestingInformationService,
    private cdr: ChangeDetectorRef,
    private router: Router,
    private gradingSV: GradingService,
    private swSV: SweetalertService
  ) {
    super(activeRoute)
   }

  ngOnInit(): void {

  }

  ngAfterViewInit(){
    this.testingInfoSV.get(this.id).pipe(
      tap(x => this.data = x),
      tap((x:any) => this.subjectList = x.testing_subjects),
      tap(x => this.subjectList = this.updateMatTable(this.subjectList? this.subjectList:[])),
      tap(x => this.cdr.detectChanges())
    ).subscribe()
  }


  applyFilter(event: Event) {
    const filterValue = (event.target as HTMLInputElement).value;
    this.subjectList.filter = filterValue.trim().toLowerCase();
  }

  onDelete(id){
    let data;
    this.gradingSV.search('?subject_uid='+id+'&testing_information_uid='+this.data.testing_information_uid).pipe(
      tap(x => data = x[0]),
      tap(x => this.swSV.confirm().pipe(
        filter(x => x.isConfirmed),
        switchMap(x => {
          return this.gradingSV.deleteData(data.grading_uid).pipe(
            tap(x => this.swSV.removeSuccess()),
            tap(x => this.testingInfoSV.get(this.id).subscribe((x:any) => {
              this.subjectList.data = x.testing_subjects
              this.cdr.detectChanges()
            })),
            tap(x => this.cdr.detectChanges())
          )
        })
      ).subscribe()),
    ).subscribe()
  }

  gradeList(id){
    this.router.navigate(['grade-summary/grade',id,this.id])
  }

  onEdit(id){
    this.router.navigate(['grade-summary/summary',id,this.id])
  }

  onView(id){
    let data;
    this.gradingSV.search('?subject_uid='+id+'&testing_information_uid='+this.data.testing_information_uid).pipe(
      tap(x => data = x[0]),
      tap(x => this.router.navigate(['grade-summary/view',data.grading_uid]))
      ).subscribe()
  }
}
