-- |
-- Module     : Simulation.Aivika.GPSS.Block.Link
-- Copyright  : Copyright (c) 2017, David Sorokin <david.sorokin@gmail.com>
-- License    : BSD3
-- Maintainer : David Sorokin <david.sorokin@gmail.com>
-- Stability  : experimental
-- Tested with: GHC 8.0.2
--
-- This module defines an analog of the GPSS block LINK.
--
module Simulation.Aivika.GPSS.Block.Link
       (linkBlock) where

import Simulation.Aivika
import Simulation.Aivika.GPSS.Block

-- | This is an analog of the GPSS construct
--
-- @LINK A,B,C@
linkBlock :: (a -> Process (Either (Block a ()) Bool))
             -- ^ try to link the transact and return either the next block to transfer
             -- or a flag indicating whether the transact process should be passivated
             -- in case of successful linking, i.e. storing in the queue
             -> Block a a
linkBlock :: (a -> Process (Either (Block a ()) Bool)) -> Block a a
linkBlock a -> Process (Either (Block a ()) Bool)
f =
  Block :: forall a b. (a -> Process b) -> Block a b
Block { blockProcess :: a -> Process a
blockProcess = \a
a ->
           do Either (Block a ()) Bool
x <- a -> Process (Either (Block a ()) Bool)
f a
a
              case Either (Block a ()) Bool
x of
                Left Block a ()
transfer ->
                  Process () -> Process a
forall a. Process () -> Process a
transferProcess (Process () -> Process a) -> Process () -> Process a
forall a b. (a -> b) -> a -> b
$
                  Block a () -> a -> Process ()
forall a b. Block a b -> a -> Process b
blockProcess Block a ()
transfer a
a
                Right Bool
False ->
                  a -> Process a
forall (m :: * -> *) a. Monad m => a -> m a
return a
a
                Right Bool
True ->
                  do Process ()
passivateProcess
                     a -> Process a
forall (m :: * -> *) a. Monad m => a -> m a
return a
a
        }