import {Component, EventEmitter, Input, OnDestroy, OnInit, Output} from '@angular/core';
import {OmpClassDao} from 'src/app/dao/omp-class.dao';
import {StudentInfoService} from 'src/app/services/student-info.service';
import {takeWhile} from 'rxjs/operators';
import {ActivatedRoute} from '@angular/router';
import {MinutePaperDao} from 'src/app/dao/minute-paper.dao';
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: OmpClassDao[];
  public openPaperList: MinutePaperDao[];

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

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

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

  private goToClassView(classCode: String) {
    this.isAlive = false;
    this.studentDataService.classCode = classCode;
    this.studentViewService.changeToDashboard(false);
    this.studentViewService.changeToClassView(true);
  }

  private goToSubmissionView(paperId: String) {
    this.studentDataService.currentPaper = this.getCurrentPaper(paperId);
    this.studentViewService.changeToDashboard(false);
    this.studentViewService.changeToSubmissionView(true);
  }

  private getCurrentPaper(paperId: String) {
    let currentPaper: MinutePaperDao = null;
    this.openPaperList.forEach(paper => {
      if (paper.paperId === paperId) {
        currentPaper = paper;
      }
    });
    return currentPaper;
  }

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

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