import { Observable, Subscription } from 'rxjs'; import { Component, OnInit, OnDestroy, Inject } from '@angular/core'; import { CourseDetails } from '../../../core/models/course-details'; import { MAT_DIALOG_DATA } from '@angular/material'; import * as selectors from '@app/degree-planner/store/selectors'; import * as utils from '@app/degree-planner/shared/utils'; import { GlobalState } from '@app/core/state'; import { Store, select } from '@ngrx/store'; import { distinctUntilChanged } from 'rxjs/operators'; import { FormBuilder, FormGroup } from '@angular/forms'; import { AddCourse, RemoveSaveForLater, } from '@app/degree-planner/store/actions/course.actions'; @Component({ selector: 'cse-course-details', templateUrl: './course-details.component.html', styleUrls: ['./course-details.component.scss'], }) export class CourseDetailsComponent implements OnInit, OnDestroy { public courseDetails: CourseDetails; public type: 'course' | 'search' | 'saved'; public selectedSearchTerm: string; public termSelector: FormGroup; public selectedSearchTerm$: Observable<string>; public droppableTermCodes$: Observable<string[]>; public searchTermSubscription: Subscription; constructor( @Inject(MAT_DIALOG_DATA) public data: any, private store: Store<GlobalState>, private fb: FormBuilder, ) { this.courseDetails = data.courseDetails; this.type = data.courseType; } ngOnInit() { this.selectedSearchTerm$ = this.store.pipe( select(selectors.getSelectedSearchTerm), ); this.droppableTermCodes$ = this.store.pipe( select(selectors.selectAllVisibleYears), utils.yearsToDroppableTermCodes(), distinctUntilChanged(utils.compareStringArrays), ); this.searchTermSubscription = this.selectedSearchTerm$.subscribe( termCode => { this.selectedSearchTerm = termCode; }, ); this.termSelector = this.fb.group({ term: this.selectedSearchTerm, }); } ngOnDestroy() { this.searchTermSubscription.unsubscribe(); } addCourseToPlan($event) { $event.preventDefault(); const termCode = this.termSelector.value.term; const subjectCode = this.courseDetails.subject.subjectCode; const courseId = this.courseDetails.courseId; switch (this.type) { case 'search': this.store.dispatch(new AddCourse({ subjectCode, courseId, termCode })); break; case 'saved': this.store.dispatch(new AddCourse({ subjectCode, courseId, termCode })); this.store.dispatch(new RemoveSaveForLater({ subjectCode, courseId })); break; } } }