import * as _ from 'lodash' ; import checkPredicate from "./predicate" ; import * as Actions from "./gameActions" ; import * as Parser from "storyboard-lang" ; import { Dispatch } from './dispatch' ; import { Node } from './node' ; import { State } from './state' ; export class Bag { constructor ( nodes , dispatch ) { this . dispatch = dispatch ; this . nodes = _ . mapValues ( nodes || { } , ( node , key ) => { if ( ! node . predicate ) { node . predicate = { } ; } var newPredicate = { track : "default" } ; const activeKeyPath = `bag.activePassageIndexes.${ node . nodeId }` ; newPredicate [ activeKeyPath ] = { "exists" : false } ; if ( ! node . allowRepeats ) { const finishedKeypath = `bag.nodeHistory.${ node . nodeId }` ; newPredicate [ finishedKeypath ] = { "exists" : false } ; } node . predicate = ( < any > Object ) . assign ( { } , node . predicate , newPredicate ) ; return new Node ( node , dispatch ) ; } ) ; } readonly nodes : { [ nodeId ] : Node ; } ; readonly dispatch : Dispatch ; checkNodes ( state ) { const filteredNodes = _ . filter ( this . nodes , ( node ) => checkPredicate ( node . predicate , state ) ) ; if ( filteredNodes . length > 0 && this . dispatch ) { const singleNodesByTrack = _ ( filteredNodes ) . groupBy ( "track" ) . mapValues ( _ . sample ) . omitBy ( ( _ , track ) => state . bag . activeTracks [ track ] ) . value ( ) ; this . dispatch ( Actions . TRIGGERED_BAG_NODES , singleNodesByTrack ) ; } } playCurrentPassage ( nodeId , state ) { const node = this . nodes [ nodeId ] ; if ( ! node ) return ; const passageIndex = state . bag . activePassageIndexes [ nodeId ] ; node . playPassage ( passageIndex ) ; } completePassage ( passageId , state ) { const nodes = _ . chain ( state . bag . activePassageIndexes ) . keys ( ) . map ( ( nodeId ) : Node => this . nodes [ nodeId ] ) . value ( ) ; const node = _ . find ( nodes , ( node ) => { return _ . chain ( node . passages ) . map ( 'passageId' ) . includes ( passageId ) . value ( ) ; } ) ; if ( ! node || ! node . passages ) return ; const currentIndex = state . bag . activePassageIndexes [ node . nodeId ] ; const currentPassage = node . passages [ currentIndex ] ; if ( passageId !== currentPassage . passageId ) return ; let found = false ; let newPassageIndex = currentIndex ; while ( ! found ) { newPassageIndex = newPassageIndex ! + 1 ; if ( _ . isUndefined ( node . passages ) || newPassageIndex >= node . passages ! . length ) { found = true ; this . dispatch ( Actions . COMPLETE_GRAPH_NODE , node . nodeId ) ; } else { const newPassage = node . passages ! [ newPassageIndex ] ; if ( ( ! newPassage . predicate ) || checkPredicate ( newPassage . predicate , state ) ) { found = true ; this . dispatch ( Actions . CHANGE_BAG_PASSAGE , [ node . nodeId , newPassageIndex ] ) ; } else { console . log ( "failed predicate" ) ; } } } } }