import { destroy , types , getParent , Instance , cast , getEnv , getSnapshot , SnapshotIn } from "mobx-state-tree" ; import { PollBase , PollChoiceBase } from "./PollBase" ; import { RootStoreEnv } from "./RootStore" ; import shortid from "shortid" ; export type PollDraftChoiceModel = Instance < typeof PollDraftChoice > ; export type PollDraftModel = Instance < typeof PollDraft > ; export const PollDraftChoice = PollChoiceBase . actions ( self => ( { setChoice ( choice ) { self . value = choice ; } , remove ( ) { const pollDraftParent = getParent < PollDraftModel > ( self , 2 ) ; pollDraftParent . removeChoice ( cast ( self ) ) ; } } ) ) ; export const PollDraft = types . compose ( PollBase , types . model ( { choices : types . optional ( types . array ( PollDraftChoice ) , [ ] ) } ) ) . actions ( self => ( { setQuestion ( question ) { self . question = question ; } , addChoice ( choice ) { self . choices . push ( { id : shortid ( ) , value : choice } ) ; } , removeChoice ( choiceToRemove ) { destroy ( choiceToRemove ) ; } , publish ( ) { const { choices , question } = getSnapshot ( self ) ; const nonEmptyChoices = choices . filter ( choice => ! ! choice ) ; if ( question && nonEmptyChoices . length > 0 ) { const env = getEnv < RootStoreEnv > ( self ) ; const pollToPublish = { question , choices : nonEmptyChoices } ; env . publishedPolls . publishDraft ( pollToPublish ) ; ( self as PollDraftModel ) . clear ( ) ; } } , clear ( ) { self . question = "" ; self . choices [ 0 ] . setChoice ( "" ) ; self . choices . splice ( 1 ) ; } } ) ) ;