-- |
-- Module      : Amazonka.Pager
-- Copyright   : (c) 2013-2021 Brendan Hay
-- License     : Mozilla Public License, v. 2.0.
-- Maintainer  : Brendan Hay <brendan.g.hay+amazonka@gmail.com>
-- Stability   : provisional
-- Portability : non-portable (GHC extensions)
module Amazonka.Pager
  ( AWSPager (..),
    AWSTruncated (..),
    stop,
    choice,
  )
where

import Amazonka.Data (ToText (..))
import Amazonka.Lens (Getter, to)
import Amazonka.Prelude
import Amazonka.Types
import qualified Data.HashMap.Strict as HashMap

-- | Specify how an 'AWSRequest' and it's associated 'Rs' response can
-- generate a subsequent request, if available.
class AWSRequest a => AWSPager a where
  page :: a -> AWSResponse a -> Maybe a

-- | Generalise IsTruncated and other optional/required
-- response pagination fields.
class AWSTruncated a where
  truncated :: a -> Bool

instance AWSTruncated Bool where
  truncated :: Bool -> Bool
truncated = Bool -> Bool
forall a. a -> a
id

instance AWSTruncated [a] where
  truncated :: [a] -> Bool
truncated = Bool -> Bool
not (Bool -> Bool) -> ([a] -> Bool) -> [a] -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null

instance AWSTruncated (HashMap k v) where
  truncated :: HashMap k v -> Bool
truncated = Bool -> Bool
not (Bool -> Bool) -> (HashMap k v -> Bool) -> HashMap k v -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. HashMap k v -> Bool
forall k v. HashMap k v -> Bool
HashMap.null

instance {-# OVERLAPPABLE #-} AWSTruncated (Maybe a) where
  truncated :: Maybe a -> Bool
truncated = Maybe a -> Bool
forall a. Maybe a -> Bool
isJust

instance {-# OVERLAPS #-} AWSTruncated (Maybe Bool) where
  truncated :: Maybe Bool -> Bool
truncated = Bool -> Maybe Bool -> Bool
forall a. a -> Maybe a -> a
fromMaybe Bool
False

stop :: AWSTruncated a => a -> Bool
stop :: a -> Bool
stop = Bool -> Bool
not (Bool -> Bool) -> (a -> Bool) -> a -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. a -> Bool
forall a. AWSTruncated a => a -> Bool
truncated

choice ::
  (Alternative f, ToText a, ToText b) =>
  (s -> f a) ->
  (s -> f b) ->
  Getter s (f Text)
choice :: (s -> f a) -> (s -> f b) -> Getter s (f Text)
choice s -> f a
f s -> f b
g = (s -> f Text) -> Optic' (->) f s (f Text)
forall (p :: * -> * -> *) (f :: * -> *) s a.
(Profunctor p, Contravariant f) =>
(s -> a) -> Optic' p f s a
to ((s -> f Text) -> Optic' (->) f s (f Text))
-> (s -> f Text) -> Optic' (->) f s (f Text)
forall a b. (a -> b) -> a -> b
$ \s
x -> (a -> Text
forall a. ToText a => a -> Text
toText (a -> Text) -> f a -> f Text
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> s -> f a
f s
x) f Text -> f Text -> f Text
forall (f :: * -> *) a. Alternative f => f a -> f a -> f a
<|> (b -> Text
forall a. ToText a => a -> Text
toText (b -> Text) -> f b -> f Text
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> s -> f b
g s
x)