{-
--------------------------------------------------------------------------------
--
-- Copyright (C) 2008 Martin Sulzmann, Edmund Lam. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.

    * Redistributions in binary form must reproduce the above
      copyright notice, this list of conditions and the following
      disclaimer in the documentation and/or other materials provided
      with the distribution.

    * Neither the name of Isaac Jones nor the names of other
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

-}

module MultiSetRewrite.ConcurrentBag where

-- a concurrent, non-blocking bag
-- ie a linked list providing n entry/exit points
-- (motivation is to allow for a more balanced access to the list elements)

import IO
import GHC.IOBase
import Monad
import Data.IORef
import Control.Concurrent
import Control.Concurrent.STM


import qualified MultiSetRewrite.ConcurrentList as L



data Bag a = Bag { maxBagIdx :: Int
                 , bagOfLists :: [L.ListHandle a] }

-- we assume a (static) listNumber of lists stored in bagList
-- IMPORTANT: Like for lists we start counting from 0

singletonBag = 0

type Iterator a = (IORef Int, Int, [L.Iterator a])

-- the components:
-- the current index of the list (in the list of iterators)
--    we're iterating over
-- the the max index
-- the list of iterators

----------------------------------------------
-- functions operating on bags


-- we create a new bag
newBag :: Int -> IO (Bag a)
newBag n = 
   do ls <- mapM (\ _ -> L.newList) [0..n]
      return (Bag {maxBagIdx = n, bagOfLists = ls})


addToBag :: Eq a => Bag a -> Int -> a -> IO (IORef (L.List a))
addToBag bag idx el = 
   if (maxBagIdx bag) < idx
   then error "addToBag: invalid bag index"
   else L.addToTail ((bagOfLists bag) !! idx) el

newIterator :: Bag a -> Int -> IO (Iterator a)
newIterator bag idx = 
   if maxBagIdx bag < idx
   then error "addToBag: invalid bag index"
   else do its <- mapM (\ l -> L.newIterator l) (bagOfLists bag)
           let (l,r) = splitAt idx its
           startIdx <- newIORef 0
           return (startIdx, maxBagIdx bag, r ++ l)

iterateBag :: Eq a => Iterator a -> IO (Maybe (IORef (L.List a)))
iterateBag (i@(curIdxPtr, maxIdx, itList)) = do
  curIdx <- readIORef curIdxPtr
  next <- L.iterateList (itList !! curIdx)
  case next of
    Just e -> return next
    Nothing ->  
      if curIdx == maxIdx then return Nothing -- exhaustive search
      else do writeIORef curIdxPtr (curIdx+1)
              iterateBag i


------------------------------------------------
-- helper stuff

printBag :: Show a => Bag a -> IO ()
printBag bag =
 let bags = bagOfLists bag
 in
    do mapM (\ i -> do putStr $ "\nEntry " ++ show i ++ ": "
                       L.printList $ bags !! i
            )
            [0..maxBagIdx bag]
       return ()

----------------------------------------------------------------
-- test cases 



test_example1 =
   do b <- newBag 4 -- 5 bags, we start counting with zero!!!
      mapM (\ entry -> do addToBag b entry (7 * entry)
                          addToBag b entry $ (7 * entry) + 1)
           [0..4]
      printBag b

      putStrLn ""

      it <- newIterator b 3
      let iterate = do n <- iterateBag it
                       case n of
                         (Just x) -> do L.printElement x
                                        iterate
                         Nothing -> return ()
      iterate