module Game.Utility where

import qualified System.Random as Rnd

import qualified Control.Monad.Trans.State as MS
import Control.Monad (liftM, )

import qualified Data.NonEmpty.Set as NonEmptySet
import qualified Data.NonEmpty as NonEmpty


readMaybe :: (Read a) => String -> Maybe a
readMaybe str =
   case reads str of
      [(a,"")] -> Just a
      _ -> Nothing

nullToMaybe :: [a] -> Maybe [a]
nullToMaybe [] = Nothing
nullToMaybe s  = Just s

-- candidate for random-utility, cf. module htam:Election, markov-chain
-- for Sets it would be more efficient to use Set.elemAt
randomSelect :: (Rnd.RandomGen g, Monad m) => [a] -> MS.StateT g m a
randomSelect items =
   liftM (items!!) $ MS.StateT $ return . Rnd.randomR (0, length items-1)

nonEmptySetToList :: NonEmptySet.T a -> [a]
nonEmptySetToList = NonEmpty.flatten . NonEmptySet.toAscList