import {Component, EventEmitter, Input, OnDestroy, OnInit, Output} from '@angular/core';
import {OmpClass} from 'src/app/dao/omp-class';
import {StudentInfoService} from 'src/app/services/student-info.service';
import {takeWhile} from 'rxjs/operators';
import {ActivatedRoute} from '@angular/router';
import {MinutePaper} from 'src/app/dao/minute-paper';
import {StudentViewService} from 'src/app/services/student-view.service';
import {StudentDataService} from '../../services/student-data.service';

@Component({
  selector: 'app-student-dashboard',
  templateUrl: './student-dashboard.component.html',
  styleUrls: ['./student-dashboard.component.css']
})
export class StudentDashboardComponent implements OnInit, OnDestroy {

  private isAlive = true;
  private studentId: String;
  public classList: OmpClass[];
  public openPaperList: MinutePaper[];

  constructor(private studentInfoService: StudentInfoService,
              private route: ActivatedRoute,
              private studentViewService: StudentViewService,
              private studentDataService: StudentDataService) {
  }

  ngOnInit(): void {
    this.route.params.subscribe(params => { this.studentId = params.id; }).add(takeWhile(() => this.isAlive));
    this.studentDataService.studentId = this.studentId;
    this.classList = [];
    this.openPaperList = [];
    this.getClassList();
    this.getOpenPapers();
    this.studentDataService.openPapers = this.openPaperList;
  }

  ngOnDestroy(): void {
    this.classList = [];
    this.openPaperList = [];
    this.isAlive = false;
  }

  private goToClassView(classCode: String) {
    this.isAlive = false;
    this.classList = [];
    this.openPaperList = [];
    this.studentDataService.classCode = classCode;
    this.studentViewService.changeDashboard(false);
    this.studentViewService.changeClassView(true);
  }

  private getClassList() {
    this.studentInfoService.getUserClasses(this.studentId).subscribe((data: OmpClass[]) => {
      data.forEach(c => this.classList.push(c));
    });
  }

  private getOpenPapers() {
    this.studentInfoService.getOpenPapers(this.studentId).subscribe((data: MinutePaper[]) => {
      data.forEach(c => this.openPaperList.push(c));
    });
  }
}