import {Component, OnDestroy, OnInit} from '@angular/core';
import {MinutePaperDao} from 'src/app/dao/minute-paper.dao';
import {StudentInfoService} from 'src/app/services/student-info.service';
import {StudentDataService} from 'src/app/services/student-data.service';
import {StudentViewService} from 'src/app/services/student-view.service';
import {Router} from '@angular/router';

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

  public openPaperList: MinutePaperDao[];
  public closedPaperList: MinutePaperDao[];
  public openClassPapers: MinutePaperDao[];
  private studentId: String;

  constructor(private studentInfoService: StudentInfoService,
              private studentViewService: StudentViewService,
              private studentDataService: StudentDataService,
              private router: Router) {
  }

  ngOnInit(): void {
    this.studentId = sessionStorage.getItem('username');
    this.openPaperList = this.studentDataService.openPapers;
    this.closedPaperList = [];
    this.openClassPapers = [];
    this.getOpenClassPapers(this.studentDataService.classCode);
    this.getSubmittedPapers(this.studentDataService.classCode);
  }

  ngOnDestroy(): void {
    this.openPaperList = [];
    this.closedPaperList = [];
    this.openClassPapers = [];
  }

  private getCurrentPaper(paperId: String) {
    let currentPaper: MinutePaperDao = null;

    this.openClassPapers.forEach(paper => {
      if (paper.paperId === paperId) {
        currentPaper = paper;
      }
    });

    this.closedPaperList.forEach(paper => {
      if (paper.paperId === paperId) {
        currentPaper = paper;
      }
    });
    return currentPaper;
  }

  private getSubmittedPapers(classCode: String) {
    this.studentInfoService.getSubmittedPapers(this.studentId, classCode).subscribe((data: MinutePaperDao[]) => {
      data.forEach(c => this.closedPaperList.push(c));
    });
  }

  private getOpenClassPapers(classCode: String) {
    this.openPaperList.forEach(e => {
      if (e.classCode === classCode) {
        this.openClassPapers.push(e);
      }
    });
  }

  public goToCompletedPage(paperId: String) {
    this.studentDataService.currentPaper = this.getCurrentPaper(paperId);
    this.router.navigate(['/completed-view']);
    this.ngOnDestroy();
  }

  public goToSubmissionView(paperId: String) {
    this.studentDataService.currentPaper = this.getCurrentPaper(paperId);
    this.router.navigate(['/submission-view']);
    this.ngOnDestroy();
  }
}