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

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

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

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

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

  courseData: CourseData | null = null;

  defaultReturnPage = Globals.pages.courses;
  possibleReturnPages = [ Globals.pages.main.path, Globals.pages.courses.path, Globals.pages.myCourses.path ];

  editCourseLink = Globals.pages.courseEdit.path;

  isPast = false;

  constructor(private route: ActivatedRoute, private courseService: CourseService, private urlService: UrlService, private loginService: LoginService) { }

  ngOnInit(): void {
    var idString = this.route.snapshot.paramMap.get('id');
    if(idString != null) {
      var id = +idString;
      if(id != NaN && id != Infinity && id != -Infinity) {
        this.loadSelectedCourse(id);
      }
    }

    this.urlService.saveCheckpoint(this.possibleReturnPages);
  }

  async loadSelectedCourse(id: number): Promise<void> {
    var data = await this.courseService.getCourseById(id);
    this.courseData = data;
    if(data?.dateEnd != null) {
      var courseDate = new Date(data?.dateEnd);
      var now = new Date();
      if(now > courseDate) {
        this.isPast = true;
      }
    }
  }

  roleAtLeast(role: string): boolean {
    return this.loginService.instructorRoleAtLeast(role);
  }

  courseRoleAtLeast(role: number): boolean {
    var user = this.loginService.getActualUserData();
    if(user != null && user.instructor != null){
      var courseUser = this.courseData?.instructors?.find(instructor => { return instructor.instructorId == user?.instructor?.ID; } );
      if(courseUser != undefined && courseUser.roleId <= role && courseUser.state == 'aktivni') {
        return true;
      }
    }
    return false;
  }

}
