import { BaseVirtualField , BaseVirtualFieldParams , BaseField } from './base' ; import { Backend } from '../base-backend' ; import { RelatedRecords , RelatedRecordParams } from '../datatypes/related-records' ; import { ListChangedEvent } from '../datatypes/data-item-list' ; import { Record , RecordRawData , RelFieldChangedEvent } from '../datatypes/record' ; import { ListModel } from '../models/list-model' ; import { SaveQuery , ChildQueryDescriber } from '../query/query' ; import { Subscription } from 'rxjs' ; export interface RelatedRecordsVirtualFieldParams extends BaseVirtualFieldParams { listModelName ? : string ; linkThrough : string ; } export class RelatedRecordsVirtualField extends BaseVirtualField { internalName = 'RelatedRecordsVirtualField' ; listModelName : string ; linkThrough : string ; constructor ( backend , params ) { super ( backend , params ) ; this . linkThrough = params . linkThrough ; } prepareValue ( record , oldValue , newValue ) { if ( newValue && newValue instanceof RelatedRecords ) { var s = newValue . changed . subscribe ( ev => { if ( ev instanceof ListChangedEvent && ev . event instanceof RelFieldChangedEvent && ev . event . value == record ) return ; record . __director__ . isChildrenChanged = true ; record . __director__ . changed . next ( new RelFieldChangedEvent ( this . name , newValue , ev ) ) ; } ) ; record . __director__ . fieldData . set ( this . name , s ) ; } } destroyValue ( record ) { if ( record . __director__ . fieldData . has ( this . name ) ) { var s = record . __director__ . fieldData . get ( this . name ) ; s . unsubscribe ( ) ; } } private _constructRRParams ( ) { return { listModel : this . backend . getListModel ( this . listModelName ) , linkThrough : this . linkThrough } ; } constructDefaultValue ( record ) { var data = record . __director__ . isNew ? [ ] : undefined ; return new RelatedRecords ( this . backend , record , this . _constructRRParams ( ) , data ) ; } fromInternalToRAW ( value ) { if ( value instanceof RelatedRecords && value . isLoaded ) { return value . extractRAWData ( ) ; } else { return null ; } ; } fromRAWtoInternal ( value , record ? ) { return new RelatedRecords ( this . backend , record , this . _constructRRParams ( ) , value ) ; } dataChanged ( fields = null , record ) { } getSaveQueries ( value ) { if ( ! value || ! value . isLoaded ) return null ; var result = [ ] ; value . items . forEach ( record => { if ( record . __director__ . isNew || record . __director__ . hasAnyChanges ) result . push ( { handle : `save__${ record . __director__ . uid }` , query : record . __director__ . getSaveQuery ( [ this . linkThrough ] ) } ) ; } ) ; value . markedToDelete . forEach ( record => { result . push ( { handle : `delete__${ record . __director__ . uid }` , query : record . __director__ . getDeleteQuery ( ) } ) ; } ) ; return result ; } cloneValue ( asNew , value ) { return value . clone ( asNew ) ; } }