import { THIS_EXPR } from '@angular/compiler/src/output/output_ast';
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import {MatDialog, MatDialogRef, MAT_DIALOG_DATA} from '@angular/material/dialog';

import { InstructorService } from '../../../services/instructor.service';
import { UrlService } from '../../../services/url.service';
import { FundService } from '../../../services/fund.service';
import { CourseService } from '../../../services/course.service';

import { ChangeRoleDialogComponent } from '../../../instructor/components/change-role-dialog/change-role-dialog.component';

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

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

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

  instructorData: InstructorData | null = null;
  rolePretty: string = '';
  fund: FundRecordData[] | null = null;
  courseHistory: CourseData[] | null = null;

  roleChangeSavingStatus: number = Globals.savingStatus.none;
  userDataSavingStatus: number = Globals.savingStatus.none;
  fundSavingStatus: number = Globals.savingStatus.none;

  previousUrl: string | undefined = undefined;

  defaultReturnPage = Globals.pages.instructors;
  possibleReturnPages = [ Globals.pages.instructors.path, Globals.pages.notifications.path ];

  editInstructorLink = Globals.pages.editInstructorProfile.path;

  //allInstructorsLink = Globals.pages.instructors;
  //notificationsLink = Globals.pages.notifications;

  constructor(private route: ActivatedRoute, private instructorService: InstructorService, private courseService: CourseService, private urlService: UrlService, private fundService: FundService, public dialog: MatDialog) { }

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

      this.fundService.fundRecords$.subscribe((data: FundRecordData[] | null) => {
        if(data != null) {
          this.fund = data?.filter(fundRecord => { return fundRecord.personId == id; });   
        } else {
          this.fund = [];
        }
      })
      this.fund = null;
      this.fundService.actualizeInstructorFund(id);

      this.courseService.courses$.subscribe((data: CourseData[] | null) => {
        if(data != null) {
          this.courseHistory = CourseFilters.filterCoursesByInstructor(data, id);   
        } else {
          this.courseHistory = [];
        }
      })
      this.courseHistory = null;
      this.courseService.actualizeInstructorCourses(id);
    }

    //this.previousUrl = this.urlService.getCheckpointUrl();

    this.urlService.saveCheckpoint(this.possibleReturnPages);

    this.instructorService.saveStatusReset();
    this.instructorService.instructorRoleSaveStatus$.subscribe( val => this.roleChangeSavingStatus = val );
    this.instructorService.instructorSaveStatus$.subscribe( val => this.userDataSavingStatus = val );
    this.fundService.saveStatusReset();
    this.fundService.fundRecordSaveStatus$.subscribe( val => this.fundSavingStatus = val );
  }

  async loadSelectedUser(id: number): Promise<void> {
    var data = await this.instructorService.getInstructorById(id);
    this.instructorData = data;
    if(data != undefined && data != null) {
      this.rolePretty = Globals.instructorRolesPretty[Globals.instructorRoles.indexOf(data.role)];
    }
  }

  openChangeRoleDialog(): void {
    if(this.instructorData != null) {
      const dialogRef = this.dialog.open(ChangeRoleDialogComponent, {
        width: '250px',
        data: { user: this.instructorData, allowedTo: 'zamestnanec' }
      });
  
      dialogRef.afterClosed().subscribe(newRole => {
        if(this.instructorData != null && newRole != undefined) {
          this.instructorService.changeInstructorRole(this.instructorData.ID, newRole);
          this.rolePretty = Globals.instructorRolesPretty[Globals.instructorRoles.indexOf(newRole)];
        }
      });
    }
  }

}
