{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses, Safe #-}

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

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

  Chatty 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.

  Chatty 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 Chatty. If not, see <http://www.gnu.org/licenses/>.
-}

-- | Provides a monad for error handling. Okay, I confess it's equal to ErrorT...
module Data.Chatty.Fail where

import Control.Applicative
import Control.Monad
import Control.Monad.Identity
import Control.Monad.Error.Class
import Control.Monad.Trans.Class

-- | The error handling monad.
newtype FailT e m a = Fail { runFailT :: m (Either e a) }
type Fail e = FailT e Identity

instance Monad m => Functor (FailT e m) where
  fmap f a = Fail $ do
     v <- runFailT a
     case v of
       Left e -> return $ Left e
       Right x -> return $ Right (f x)

instance Monad m => Applicative (FailT e m) where
  pure = return
  (<*>) = ap

instance Monad m => Monad (FailT e m) where
  return a = Fail $ return $ Right a
  m >>= f = Fail $ do
    v <- runFailT m
    case v of
      Left e -> return $ Left e
      Right x -> runFailT $ f x

instance MonadTrans (FailT e) where
  lift m = Fail $ do
    a <- m
    return $ Right a

instance Monad m => MonadError e (FailT e m) where
  throwError e = Fail $ return $ Left e
  catchError m h = Fail $ do
    v <- runFailT m
    case v of
      Left e -> runFailT $ h e
      Right x -> return v