{-# LANGUAGE RankNTypes, FlexibleContexts, FlexibleInstances, RecordWildCards #-}

{-
  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 utility functions for composing skills
module Game.Antisplice.Skills (
  -- * Utility types
  Condition(..),
  Consumer(..),
  Skill (..),
  Recipe (..),
  ToConsumer (toConsumer),
  -- * Compositors
  Extensible(..),
  (>!+), (!+>), (>!+>),
  -- * Builders
  skill,
  recipe,
  validConsumer,
  validCondition,
  (#->),
  (#->>),
  -- * Sample consumers
  focusDirectC,
  optionallyFocusDirectC,
  callRecipe,
  -- * Final wrappers
  runConsumer,
  wrapSkills,
  wrapRecipes,
  ) where

import Control.Arrow
import Control.Monad
import Control.Monad.Identity
import Control.Monad.Error.Class
import Data.Monoid
import Game.Antisplice.Action
import Game.Antisplice.Call
import Game.Antisplice.Errors
import Game.Antisplice.Monad.Dungeon
import Game.Antisplice.Monad.Vocab
import Game.Antisplice.Rooms
import Game.Antisplice.Stats
import Game.Antisplice.Utils.None
import Game.Antisplice.Utils.Counter
import Game.Antisplice.Utils.Atoms

-- | A wrapper type for skill execution preconditions.
newtype Condition = Condition { runCondition' :: InvokableP }
runCondition :: Condition -> [String] -> ChattyDungeonM Bool
runCondition c ps = runPrerequisite $ runCondition' c ps

instance Monoid Condition where
  mempty = Condition $ \_ -> Prerequisite $ return True
  a `mappend` b = Condition $ \ps -> Prerequisite $ do
    a' <- runCondition a ps
    b' <- runCondition b ps
    return (a' && b')

instance IsAction Condition where
  p #&& q = Condition $ \ps -> Prerequisite $ do
    a <- runCondition p ps
    if a then runCondition q ps
         else return False
  p #|| q = Condition $ \ps -> Prerequisite $ do
    a <- runCondition p ps
    if a then return True
         else runCondition q ps
  p !&& q = p <> q
  p !|| q = Condition $ \ps -> Prerequisite $ do
    a <- runCondition p ps
    b <- runCondition q ps
    return (a || b)
              
instance None Condition where
  none = mempty

-- | A skill. Build it using the '!+' compositor and the 'skill' function.
data Skill = Skill {
    skillConditionOf :: !Condition,
    skillActionOf :: !Invokable,
    skillNameOf :: !String
  }

-- | A recipe. Build it using the '!+' compositor and the 'recipe' function.
data Recipe = Recipe {
    recipeConditionOf :: !Condition,
    recipeActionOf :: !Invokable,
    recipeMethodOf :: !RecipeMethod,
    recipeNameOf :: !String
  }

-- | A single consumer. Build it using 'bareAction', 'bareCondition' and monoid concatenation.
data Consumer = Consumer !Condition !Invokable

instance Monoid Consumer where
  mempty = Consumer none noneM
  (Consumer c1 a1) `mappend` (Consumer c2 a2) = Consumer (c1 <> c2) (\ps -> Handler (runHandler (a1 ps) >> runHandler (a2 ps)))

instance IsAction Consumer where
  (Consumer c1 a1) #&& (Consumer c2 a2) = Consumer (c1 #&& c2) (\ps -> Handler (runHandler (a1 ps) >> runHandler (a2 ps)))
  (Consumer c1 a1) #|| (Consumer c2 a2) = Consumer (c1 #|| c2) (\ps -> Handler (runCondition c1 ps >>= \q -> if q then runHandler (a1 ps) else runHandler (a2 ps)))
  p !&& q = p <> q
  (Consumer c1 a1) !|| (Consumer c2 a2) = Consumer (c1 !|| c2) (\ps -> Handler (runCondition c1 ps >>= \q -> runCondition c2 ps >> if q then runHandler (a1 ps) else runHandler (a2 ps)))

instance None Consumer where
  none = mempty

-- | Focus direct object
focusDirectC :: Consumer
{-focusDirectC = bareAction (\p -> case p of
                                   SkillParam Getters{..} (Just o) _ _ _ _ -> focusOpponent =<< return.objectIdOf =<< dispget getSeenObject o
                                   _ -> throwError UnintellegibleError)-}
focusDirectC = validConsumer SeenObject $ \o -> focusOpponent $ objectIdOf o

-- | Optionally ocus direct object (obligatory if none is focused yet)
optionallyFocusDirectC :: Consumer
{-optionallyFocusDirectC = bareAction (\p -> case p of
                                        SkillParam Getters{..} (Just o) _ _ _ _ -> focusOpponent =<< return.objectIdOf =<< dispget getSeenObject o
                                        SkillParam _ Nothing _ _ _ _ -> do
                                          o <- liftM playerOpponentOf getPlayerState
                                          case o of
                                            FalseObject -> throwError UnintellegibleError
                                            _ -> noneM)-}
optionallyFocusDirectC = focusDirectC #|| validConsumer Nil (\_ ->  do
                                                                o <- liftM playerOpponentOf getPlayerState
                                                                case o of
                                                                  FalseObject -> throwError UnintellegibleError
                                                                  _ -> noneM)

-- | Typeclass for everything that may act as a consumer.
class ToConsumer c where
  toConsumer :: c -> Consumer

instance ToConsumer Consumer where
  toConsumer = id

instance ToConsumer Skill where
  toConsumer (Skill c a n) = Consumer c a

instance ToConsumer Recipe where
  toConsumer (Recipe c a m n) = Consumer c a

instance ToConsumer HandlerBox where
  toConsumer t = Consumer none (\_ -> t)

instance ToConsumer Condition where
  toConsumer c = Consumer c (\_ -> Handler $ return none)

instance ToConsumer PrerequisiteBox where
  toConsumer p = Consumer (Condition $ \_ -> p) (\_ -> Handler $ return none)

instance ToConsumer Action where
  toConsumer a = Consumer (Condition $ \_ -> Prerequisite $ askAction a) (\_ -> Handler $ runAction a)

-- | Typeclass for everything that may be extended by consumers using !+
class Extensible e where
  infixl 5 !+
  -- | Add a consumer to the skill.
  (!+) :: ToConsumer c => e -> c -> e

instance Extensible Skill where  
  s !+ c = s !+! toConsumer c
    where (Skill c a n) !+! (Consumer c1 a1) = Skill (c <> c1) (\ps -> Handler (runHandler (a ps) >> runHandler (a1 ps))) n

instance Extensible Recipe where
  s !+ c = s !+! toConsumer c
    where (Recipe c a m n) !+! (Consumer c1 a1) = Recipe (c <> c1) (\ps -> Handler (runHandler (a ps) >> runHandler (a1 ps))) m n

instance Extensible Consumer where
  s !+ c = s <> toConsumer c

infixl 5 >!+
-- | Add a consumer to the monadic extensible
(>!+) :: (ToConsumer c,Monad m,Extensible e) => m e -> c -> m e
m >!+ c = do
  s <- m
  return (s !+ c)

infixl 5 !+>
-- | Add a monadic consumer to the extensible
(!+>) :: (ToConsumer c,Monad m,Extensible e) => e -> m c -> m e
s !+> m = do
  c <- m
  return (s !+ c)

infixl 5 >!+>
-- | Add a monadic consumer to the monadic extensible
(>!+>) :: (ToConsumer c,Monad m,Extensible e) => m e -> m c -> m e
ms >!+> mc = do
  s <- ms
  c <- mc
  return (s !+ c)

-- | Build a consumer using new-style input validation
validConsumer :: (Append r Nil r,CallMask m r,Tuplify r t) => m -> (t -> Handler) -> Consumer
validConsumer m h = Consumer
  (Condition $ \ps -> Prerequisite $ tryMask m ps)
  (\ps -> Handler $ do
      t <- processMask m ps
      h t)

infixr 7 #->
-- | Infix version of validConsumer
(#->) :: (Append r Nil r, CallMask m r, Tuplify r t) => m -> (t -> Handler) -> Consumer
(#->) = validConsumer

infixr 7 #->>
-- | Infix version of validConsumer, swallowing the empty handler parameter
(#->>) :: CallMask m Nil => m -> Handler -> Consumer
m #->> h = m #-> const h

-- | Build a condition using new-style input validation
validCondition :: (Append r Nil r, CallMask m r, Tuplify r t) => m -> (t -> Prerequisite) -> Condition
validCondition m p =
  Condition (\ps -> Prerequisite $ tryMask m ps) <>
  Condition (\ps -> Prerequisite $ do t <- processMask m ps; p t)

-- | Dispatch the remaining part of the line as a recipe call
callRecipe :: RecipeMethod -> Consumer
{-callRecipe m =  Consumer none (\f ps -> Handler $ case ps of
                                    [] -> throwError UnintellegibleError
                                    p:ps -> do
                                      ste <- totalStereo
                                      case stereoRecipeBonus ste p of
                                        Nothing -> throwError CantCastThatNowError
                                        Just r -> runHandler $ r m f ps)-}
callRecipe m = CatchAny :-: Remaining :-: Nil #->
  \(p,ps) -> do
      ste <- totalStereo
      case stereoRecipeBonus ste p of
        Nothing -> throwError CantCastThatNowError
        Just r -> runHandler $ r m ps

-- | Build a bogus skill that does nothing but has a name. Use this with '!+' to build powerful skills.
skill :: String -> Skill
skill = Skill none noneM

-- | Build a bogus recipe that does nothing has a name and a usage method. Use this with '!+' to build powerful recipes.
recipe :: RecipeMethod -> String -> Recipe
recipe = Recipe none noneM

-- | Wrap the skills into a form that is accepted by stereotypes.
wrapSkills :: [Skill] -> String -> Maybe Invokable
wrapSkills sk n =
  case filter ((==n).skillNameOf) sk of
    [] -> Nothing
    sk:_ -> Just $ runConsumer sk

-- | Wrap the recipes into a form that is accepted by stereotypes.
wrapRecipes :: [Recipe] -> String -> Maybe (RecipeMethod -> Invokable)
wrapRecipes sk n =
  case filter ((==n).recipeNameOf) sk of
    [] -> Nothing
    sk:_ -> Just $ \m -> if m == recipeMethodOf sk then runConsumer sk else \_ -> Handler $ throwError WrongMethodError

-- | Run the given consumer
runConsumer :: ToConsumer c => c -> Invokable
runConsumer c = runConsumer' $ toConsumer c
  where runConsumer' :: Consumer -> Invokable
        runConsumer' (Consumer c a) = \ps -> Handler $ do
          b <- runCondition c ps
          unless b $ throwError CantCastThatNowError
          runHandler $ a ps