import { Bot , BotsState } from './Bot' ; import { calculateBotValue , isDestroyable } from './BotCalculations' ; import { BotCalculationContext } from './BotCalculationContext' ; import { botRemoved , BotAction , ApplyStateAction , botAdded , botUpdated , AddBotAction , RemoveBotAction , UpdateBotAction , } from './BotEvents' ; import { uniq } from 'lodash' ; param calc param bot export function calculateDestroyBotEvents ( calc , bot ) { if ( ! isDestroyable ( calc , bot ) ) { return [ ] ; } let events = [ ] ; let id ; if ( typeof bot === 'object' ) { id = bot . id ; } else if ( typeof bot === 'string' ) { id = bot ; } if ( id ) { events . push ( botRemoved ( id ) ) ; } destroyChildren ( calc , events , id ) ; return events ; } function destroyChildren ( calc , events , id ) { const result = calc . objects . filter ( ( o ) => calculateBotValue ( calc , o , 'creator' ) === id ) ; result . forEach ( ( child ) => { if ( ! isDestroyable ( calc , child ) ) { return ; } events . push ( botRemoved ( child . id ) ) ; destroyChildren ( calc , events , child . id ) ; } ) ; } param actions export function resolveRejectedActions ( actions ) { let rejections = new Set ( ) ; let final = [ ] ; for ( let i = actions . length - 1 ; i >= 0 ; i -- ) { const action = actions [ i ] ; if ( rejections . has ( action ) ) { rejections . delete ( action ) ; } else if ( action . type === 'reject' ) { for ( let a of action . actions ) { rejections . add ( < BotAction > a ) ; } } else { final . unshift ( action ) ; } } return uniq ( final ) ; } param currentState param event export function breakIntoIndividualEvents ( currentState , event ) { let actions = [ ] as ( AddBotAction | RemoveBotAction | UpdateBotAction ) [ ] ; let update = event . state ; for ( let id in update ) { const botUpdate = update [ id ] ; const currentBot = currentState [ id ] ; if ( ! currentBot && botUpdate ) { actions . push ( botAdded ( botUpdate ) ) ; } else if ( currentBot && ! botUpdate ) { actions . push ( botRemoved ( id ) ) ; } else if ( currentBot && botUpdate ) { actions . push ( botUpdated ( id , botUpdate ) ) ; } } return actions ; }