-- |
-- Module     : Simulation.Aivika.Trans.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.Trans.GPSS.Block.Link
       (linkBlock) where

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

-- | This is an analog of the GPSS construct
--
-- @LINK A,B,C@
linkBlock :: MonadDES m
             => (a -> Process m (Either (Block m 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 m a a
{-# INLINABLE linkBlock #-}
linkBlock :: (a -> Process m (Either (Block m a ()) Bool)) -> Block m a a
linkBlock a -> Process m (Either (Block m a ()) Bool)
f =
  Block :: forall (m :: * -> *) a b. (a -> Process m b) -> Block m a b
Block { blockProcess :: a -> Process m a
blockProcess = \a
a ->
           do Either (Block m a ()) Bool
x <- a -> Process m (Either (Block m a ()) Bool)
f a
a
              case Either (Block m a ()) Bool
x of
                Left Block m a ()
transfer ->
                  Process m () -> Process m a
forall (m :: * -> *) a. MonadDES m => Process m () -> Process m a
transferProcess (Process m () -> Process m a) -> Process m () -> Process m a
forall a b. (a -> b) -> a -> b
$
                  Block m a () -> a -> Process m ()
forall (m :: * -> *) a b. Block m a b -> a -> Process m b
blockProcess Block m a ()
transfer a
a
                Right Bool
False ->
                  a -> Process m a
forall (m :: * -> *) a. Monad m => a -> m a
return a
a
                Right Bool
True ->
                  do Process m ()
forall (m :: * -> *). MonadDES m => Process m ()
passivateProcess
                     a -> Process m a
forall (m :: * -> *) a. Monad m => a -> m a
return a
a
        }