import { Injectable } from '@angular/core' ; import { FormBuilder , FormGroup } from '@angular/forms' ; import { IUnit } from '../../../../../../shared/models/units/IUnit' ; import { ICourse } from '../../../../../../shared/models/ICourse' ; import { ILecture } from '../../../../../../shared/models/ILecture' ; import { MatDialog } from '@angular/material' ; import { FreeTextUnitService , NotificationService , UnitService } from './data.service' ; import { SnackBarService } from './snack-bar.service' ; @ Injectable ( ) export class UnitFormService { public unitForm : FormGroup ; public model : IUnit ; public course : ICourse ; public lecture : ILecture ; public headline : string ; public unitInfoText : string ; /**
     * if false is returned, submit will be cancelled
     */ public beforeSubmit : ( ) => Promise < boolean > ; constructor ( private formBuilder , private freeTextUnitService , private unitService , private snackbar , public dialog , private notificationService ) { this . reset ( ) ; } reset ( ) { this . unitForm = new FormGroup ( { } ) ; this . beforeSubmit = undefined ; this . headline = null ; this . unitInfoText = null ; } async save ( onDone ) { if ( this . beforeSubmit ) { const success = await this . beforeSubmit ( ) ; if ( ! success ) { return ; } } if ( ! this . unitForm . valid ) { const snackErrMessage = `Given input is not valid. Please fill fields correctly.` ; this . snackbar . openShort ( snackErrMessage ) ; return ; } this . model = { ... this . model , ... this . unitForm . getRawValue ( ) } ; const reqObj = { lectureId : this . lecture . _id , model : this . model } ; let isUpdate ; let promise ; if ( reqObj . model . _id ) { isUpdate = true ; promise = this . unitService . updateItem ( this . model ) ; } else { isUpdate = false ; promise = this . unitService . createItem ( reqObj ) ; } try { const responseUnit = await promise ; const snackSuccMessage = `Unit ${ this . model . name ? `'${ this . model . name }'` : '' } successfully ${ isUpdate ? 'updated' : 'created' }` ; const notifyMessage = `Course '${ this . course . name }' has ${ isUpdate ? 'a new' : 'an updated' } Unit '${ this . model . name }'` ; this . snackbar . openShort ( snackSuccMessage ) ; onDone ( ) ; if ( this . model . visible ) { this . notificationService . createItem ( { targetId : responseUnit . _id , targetType : 'unit' , text : notifyMessage } ) ; } } catch ( err ) { const snackErrMessage = `Couldn't ${ isUpdate ? 'update' : 'create' } Unit '${ this . model . name ? `'${ this . model . name }'` : '' }'` ; this . snackbar . openShort ( snackErrMessage ) ; } } }