{-# LANGUAGE Safe #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UnicodeSyntax #-}

module Control.Concurrent.STM.Queue
( Queue(..)
, awaitQueueEmpty
) where

import Control.Concurrent.STM
import Control.Concurrent.STM.TBMQueue
import Control.Concurrent.STM.TMQueue
import Control.Monad

class Queue q where
  type QueueValue q α

  readQueue
    ∷ q α
    → STM (QueueValue q α)

  tryReadQueue
    ∷ q α
    → STM (Maybe (QueueValue q α))

  peekQueue
    ∷ q α
    → STM (QueueValue q α)

  tryPeekQueue
    ∷ q α
    → STM (Maybe (QueueValue q α))

  writeQueue
    ∷ q α
    → α
    → STM ()

  unGetQueue
    ∷ q α
    → α
    → STM ()

  isEmptyQueue
    ∷ q α
    → STM Bool

instance Queue TQueue where
  type QueueValue TQueue α = α
  readQueue = readTQueue
  tryReadQueue = tryReadTQueue
  peekQueue = peekTQueue
  tryPeekQueue = tryPeekTQueue
  writeQueue = writeTQueue
  unGetQueue = unGetTQueue
  isEmptyQueue = isEmptyTQueue

instance Queue TBQueue where
  type QueueValue TBQueue α = α
  readQueue = readTBQueue
  tryReadQueue = tryReadTBQueue
  peekQueue = peekTBQueue
  tryPeekQueue = tryPeekTBQueue
  writeQueue = writeTBQueue
  unGetQueue = unGetTBQueue
  isEmptyQueue = isEmptyTBQueue

instance Queue TMQueue where
  type QueueValue TMQueue α = Maybe α
  readQueue = readTMQueue
  tryReadQueue = tryReadTMQueue
  peekQueue = peekTMQueue
  tryPeekQueue = tryPeekTMQueue
  writeQueue = writeTMQueue
  unGetQueue = unGetTMQueue
  isEmptyQueue = isEmptyTMQueue

instance Queue TBMQueue where
  type QueueValue TBMQueue α = Maybe α
  readQueue = readTBMQueue
  tryReadQueue = tryReadTBMQueue
  peekQueue = peekTBMQueue
  tryPeekQueue = tryPeekTBMQueue
  writeQueue = writeTBMQueue
  unGetQueue = unGetTBMQueue
  isEmptyQueue = isEmptyTBMQueue

-- | Block until a queue is empty.
awaitQueueEmpty
  ∷ Queue q
  ⇒ q α
  → STM ()
awaitQueueEmpty =
  isEmptyQueue >=> check

