{-# LANGUAGE FlexibleInstances #-}

{-
  This module is part of Antisplice.
  Copyleft (c) 2014 Marvin Cohrs

  All wrongs reversed. Sharing is an act of love, not crime.
  Please share Antisplice with everyone you like.

  Antisplice is free software: you can redistribute it and/or modify
  it under the terms of the GNU Affero General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.

  Antisplice is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  GNU Affero General Public License for more details.

  You should have received a copy of the GNU Affero General Public License
  along with Antisplice. If not, see <http://www.gnu.org/licenses/>.
-}

-- | Provides a typeclass for everything that may carry a void value
module Game.Antisplice.Utils.None where

import Data.Maybe
import Data.Text (pack, Text)

-- | Typeclass for everything that may carry a void value
class None n where
  none :: n

instance None [a] where
  none = []

instance None (Maybe a) where
  none = Nothing

instance None () where
  none = ()

instance None Text where
  none = pack ""

instance None (a -> a) where
  none = id

instance Monad m => None (a -> m a) where
  none = return

instance None Int where
  none = 0

instance None Integer where
  none = 0

instance None Bool where
  none = False

-- | Wrap the void into a monad.
noneM :: (Monad m,None n) => m n
noneM = return none

-- | Join a maybe into the underlying type. 'Nothing' becomes 'none'.
joinMaybe :: None n => Maybe n -> n
joinMaybe (Just j) = j
joinMaybe Nothing = none

-- | Wrap the value into a maybe. 'none' becomes 'Nothing'.
expandMaybe :: (Eq n,None n) => n -> Maybe n
expandMaybe n
  | n == none = Nothing
  | otherwise = Just n

-- | Clean the maybe by pulling wrapped 'none's to the outside (as a 'Nothing').
cleanMaybe :: (Eq n,None n) => Maybe n -> Maybe n
cleanMaybe = expandMaybe . joinMaybe

-- | Eliminate all void elements from the list.
reduce :: (Eq n,None n) => [n] -> [n]
reduce = filter (/=none)

-- | Eliminate all 'Nothing's from the list and unjust all remaining values.
reduceMaybe :: [Maybe a] -> [a]
reduceMaybe = map unjust . filter isJust
  where unjust (Just j) = j