import { assertExists } from '@ulangi/assert' ; import { Mutable } from '@ulangi/extended-types' ; import { ActionType , createAction } from '@ulangi/ulangi-action' ; import { ErrorBag , Set } from '@ulangi/ulangi-common/interfaces' ; import { EventBus , group , on , once } from '@ulangi/ulangi-event' ; import { ObservableSetFormState } from '@ulangi/ulangi-observable' ; export class EditSetDelegate { private eventBus : EventBus ; private setFormState : ObservableSetFormState ; public constructor ( eventBus , setFormState ) { this . eventBus = eventBus ; this . setFormState = setFormState ; } public saveEdit ( originalSet , callback ) { const learningLanguageCode = assertExists ( this . setFormState . learningLanguageCode , 'Cannot save edit because learningLanguageCode is null' ) ; const translatedToLanguageCode = assertExists ( this . setFormState . translatedToLanguageCode , 'Cannot save edit because translatedToLanguageCode is null' ) ; const setName = this . setFormState . setName === '' ? this . setFormState . autoGeneratedSetName : this . setFormState . setName ; const editedSet = { setName , learningLanguageCode : learningLanguageCode , translatedToLanguageCode : translatedToLanguageCode , } ; let setDiff = this . getSetDiff ( originalSet , editedSet ) ; this . eventBus . pubsub ( createAction ( ActionType . SET__EDIT , { set : { setId : this . setFormState . setId , ... setDiff , } , } ) , group ( on ( ActionType . SET__EDITING , callback . onSaving ) , once ( ActionType . SET__EDIT_SUCCEEDED , ( { set } ) : void => callback . onSaveSucceeded ( set ) ) , once ( ActionType . SET__EDIT_FAILED , ( errorBag ) : void => callback . onSaveFailed ( errorBag ) ) ) ) ; } private getSetDiff ( originalSet , editedSet ) { const diff = { } ; for ( let key in editedSet ) { if ( editedSet . hasOwnProperty ( key ) ) { if ( key === 'setName' || key === 'learningLanguageCode' || key === 'translatedToLanguageCode' ) { const editedValue = editedSet [ key ] ; if ( editedValue !== originalSet [ key ] ) { diff [ key ] = editedValue ; } } } } return diff ; } }