import { Component, Inject, OnInit } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { ReplaySubject } from 'rxjs';

import { InstructorService } from '../../../services/instructor.service';

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

import * as Globals from '../../../globals';
import { createUrlResolverWithoutPackagePrefix } from '@angular/compiler';

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

  allCourseInstructors: CourseInstructorData[] = [];
  newCourseInstructors: CourseInstructorData[] = [];
  instructorRequests: CourseInstructorData[] = [];

  role: number = 0;
  roleName: string = '';

  instructorSearchText: string = "";
  allInstructors: InstructorData[] | null = null;
  notInvolvedInstructors: InstructorData[] | null = null;
  filteredInstructors: ReplaySubject<InstructorData[]> = new ReplaySubject<InstructorData[]>(1);

  constructor(public dialogRef: MatDialogRef<CourseInstructorsDialogComponent>, 
              @Inject(MAT_DIALOG_DATA) public data: { instructors: CourseInstructorData[], role: number },
              private instructorService: InstructorService) { 

    this.role = data.role;
    this.roleName = Globals.instructorCourseRoles[this.role];

    //this.newCourseInstructors = JSON.parse(JSON.stringify(data.instructors));
    this.allCourseInstructors = data.instructors;
    this.newCourseInstructors = data.instructors.filter(instructor => { return instructor.state == 'aktivni' && instructor.roleId == data.role; });
    this.newCourseInstructors.forEach(courseInstructor => { courseInstructor.instructorName = ''; });
    if(this.newCourseInstructors.length == 0) {
      this.addPosition();
    }

    this.instructorRequests = data.instructors.filter(instructor => { return instructor.state == 'zadost' && instructor.roleId == data.role; });

    // nacteni vsech dostupnych instruktoru
    this.instructorService.allInstructors$.subscribe((data: InstructorData[] | null) => {
      this.allInstructors = data;
      this.actualizeNotInvolvedInstructors();
      if(this.notInvolvedInstructors != null) {
        this.filteredInstructors.next(this.notInvolvedInstructors);
      }
    })
    this.instructorService.actualizeAllInstructors(); 
  }

  ngOnInit(): void {
  }

  close(): void {
    this.dialogRef.close();
  }

  submit(): void {
    // ostraneni prazdnych zaznamu
    this.newCourseInstructors = this.newCourseInstructors.filter(courseInstructor => { return courseInstructor.instructorId != 0; })
    // doplneni jmen instruktoru
    this.newCourseInstructors.forEach(courseInstructor => { 
      var index = this.allInstructors?.findIndex(instructor => { return instructor.ID == courseInstructor.instructorId; });
      if(index != undefined && this.allInstructors != null && this.allInstructors[index] != undefined) {
        courseInstructor.instructorName = this.allInstructors[index].firstname + ' ' + this.allInstructors[index].lastname; 
      }
    });
    this.dialogRef.close(this.newCourseInstructors);
  }

  addPosition(): void {
    this.newCourseInstructors.push({ instructorId: 0, roleId: this.role, instructorName: '', state: 'aktivni', evaluation: null });
  }

  chooseInstructor(id: number): void {
    var found = this.newCourseInstructors.find(instructor => { return instructor.instructorId == 0; });
    if(found != undefined) {
      found.instructorId = id;
      found.roleId = this.role;
      found.instructorName = '';
      found.state = 'aktivni';
    } else {
      this.newCourseInstructors.push({ instructorId: id, roleId: this.role, instructorName: '', state: 'aktivni', evaluation: null });
    }
  }

  removePosition(i: number): void {
    //delete this.newCourseInstructors[i];
    this.newCourseInstructors.splice(i, 1);
    if(this.newCourseInstructors.length == 0) {
      this.addPosition();
    }
  }

  actualizeNotInvolvedInstructors() {
    var filtered = this.allInstructors?.filter(instructor => { 
      var result = Globals.roleIsAtLeast(instructor.role, 'instruktor');
      this.allCourseInstructors.forEach(courseInstructor => {
        if(courseInstructor.instructorId == instructor.ID && courseInstructor.state == 'aktivni' && courseInstructor.roleId != this.role) {
          result = false;
        }
      });
      return result;
    });
    if(filtered != undefined) {
      this.notInvolvedInstructors = filtered;
    } else {
      this.notInvolvedInstructors = [];
    }  
  }

  filterInstructors(): void {
    if(this.notInvolvedInstructors != null) {
      this.filteredInstructors.next(this.notInvolvedInstructors.filter(instructor => (instructor.firstname + ' ' + instructor.lastname).toLowerCase().indexOf(this.instructorSearchText.toLowerCase()) > -1));
    }
  }

}
