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

import { share, tap } from 'rxjs/operators';

import { CourseService } from '../../../services/course.service';
import { LoginService } from '../../../services/login.service';

import { CourseData } from '../../../structures/course-data';
import { InstructorData } from '../../../structures/instructor-data';

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

@Component({
  selector: 'app-my-courses-page',
  templateUrl: './my-courses-page.component.html',
  styleUrls: ['./my-courses-page.component.scss']
})
export class MyCoursesPageComponent implements OnInit {

  myCourses: CourseData[] | null = [];

  invalidation = 0; // promenna slouzici pro invalidaci dat ve vlozene komponente. Kurzy jsou predavany jako pole a u toho Angular nedetekuje zmeny uvnitr pole.

  //currentMyCurses = this.courseService.nearestFreeSpotsChange.pipe(share());

  constructor(private courseService: CourseService, private loginService: LoginService) { 
    // this.courseService.getNearestFreeSpots().subscribe(
    //   resp => this.afterCoursesLoaded(resp)
    // );

    // this.myCourses = this.courseService.nearestFreeSpots;
    // this.courseService.nearestFreeSpotsChange.subscribe(value => {this.afterCoursesLoaded(value)});
    // this.courseService.nearestFreeSpotsChange.pipe(share(), tap(value => this.myCourses = value));
    // this.courseService.actualizeNearestFreeSpots();

    this.courseService.courses$.subscribe((courses: CourseData[] | null) => {
      if(courses != null) {
        var userData = this.loginService.getActualUserData();
        if(userData != null) {
          if(userData.instructor != null) {
            this.myCourses = CourseFilters.filterCoursesByInstructor(courses, userData.instructor.ID);
          } else {
            this.myCourses = [];
          }
        } else {
          this.myCourses = [];
        }
      } else {
        this.myCourses = null;
      }
      this.invalidation++;
    })
    this.courseService.actualizeMyCourses();
  }

  ngOnInit(): void {
  }

  afterCoursesLoaded(value: CourseData[]): void {
    this.myCourses = value;
  }

}
