import { Component, OnInit, Input, ViewChild } from '@angular/core';
import {MatTable} from '@angular/material/table'; 
import { Observable } from 'rxjs';

import { CourseData } from '../../../structures/course-data';
import { SchoolData } from '../../../structures/school-data';
import { CourseThemeData } from '../../../structures/course-theme-data';

import { SchoolService } from '../../../services/school.service';
import { CourseThemeService } from '../../../services/course-theme.service';

import * as Globals from '../../../globals';

@Component({
  selector: 'app-courses-basic-table',
  templateUrl: './courses-basic-table.component.html',
  styleUrls: ['./courses-basic-table.component.scss']
})

export class CoursesBasicTableComponent implements OnInit {

  @Input() courses: CourseData[] = [];
  @Input() invalidation: number = 0; // promenna slouzici pro invalidaci dat ve vlozene komponente. Kurzy jsou predavany jako pole a u toho Angular nedetekuje zmeny uvnitr.

  @ViewChild(MatTable) table!: MatTable<CourseData>;

  courseThemes: CourseThemeData[] | null = null;
  schools: SchoolData[] | null = null;

  detailLink: string = Globals.pages.courseDetail.path;

  displayedColumns: string[] = ['date', 'class', 'schoolName', 'themeName', 'link'];

  constructor(private schoolService: SchoolService, private courseThemeService: CourseThemeService) {
      // nacteni skol
      this.schoolService.allSchools$.subscribe((schools: SchoolData[] | null) => {
        this.schools = schools;
      });
      this.schoolService.actualizeAllSchools();
  
      // nacteni temat kurzu
      this.courseThemeService.courseThemes$.subscribe((themes: CourseThemeData[] | null) => {
        this.courseThemes = themes;
      });
      this.courseThemeService.actualizeCourseThemes();
  }

  ngOnInit(): void {
  }

  ngOnChanges() {
     if(this.table != undefined) {
      this.table.renderRows();
     }
  }  

  getSchoolNameById(id: number | null): string {
    if(this.schools != null && id != null) {
      var found = this.schools.find(school => { return school.ID == id; });
      if(found != undefined) {
        return found.name;
      }
    }
    return '';
  } 

  getThemeNameById(id: number | null): string {
    if(this.courseThemes != null && id != null) {
      var found = this.courseThemes.find(theme => { return theme.ID == id; });
      if(found != undefined) {
        return found.name;
      }
    }
    return '';
  } 

}
