{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# LANGUAGE Trustworthy, FlexibleInstances, UnicodeSyntax #-}

-- | This module exports all the things at the same time, plus a utility
-- function.
module Network.HTTP.Link (
  module Network.HTTP.Link.Types
, module Network.HTTP.Link.Writer
, module Network.HTTP.Link.Parser
, lnk
) where

import           Control.Error.Util (hush)
import           Data.Text (Text, pack)
import           Data.Text.Encoding
import safe      Network.HTTP.Link.Parser
import safe      Network.HTTP.Link.Types
import safe      Network.HTTP.Link.Writer
import           Web.HttpApiData

instance (IsURI uri)  ToHttpApiData [Link uri] where
  toUrlPiece :: [Link uri] -> Text
toUrlPiece = Text -> Text
forall a. ToHttpApiData a => a -> Text
toUrlPiece (Text -> Text) -> ([Link uri] -> Text) -> [Link uri] -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [Link uri] -> Text
forall uri. IsURI uri => [Link uri] -> Text
writeLinkHeader
  toHeader :: [Link uri] -> ByteString
toHeader = Text -> ByteString
encodeUtf8 (Text -> ByteString)
-> ([Link uri] -> Text) -> [Link uri] -> ByteString
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [Link uri] -> Text
forall uri. IsURI uri => [Link uri] -> Text
writeLinkHeader

instance (IsURI uri)  ToHttpApiData (Link uri) where
  toUrlPiece :: Link uri -> Text
toUrlPiece = Text -> Text
forall a. ToHttpApiData a => a -> Text
toUrlPiece (Text -> Text) -> (Link uri -> Text) -> Link uri -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Link uri -> Text
forall uri. IsURI uri => Link uri -> Text
writeLink
  toHeader :: Link uri -> ByteString
toHeader = Text -> ByteString
encodeUtf8 (Text -> ByteString)
-> (Link uri -> Text) -> Link uri -> ByteString
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Link uri -> Text
forall uri. IsURI uri => Link uri -> Text
writeLink

-- | Construct a Link.
lnk  (IsURI uri)  String  [(LinkParam, Text)]  Maybe (Link uri)
lnk :: String -> [(LinkParam, Text)] -> Maybe (Link uri)
lnk String
u [(LinkParam, Text)]
r = (uri -> Link uri) -> Maybe uri -> Maybe (Link uri)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (\uri
x  uri -> [(LinkParam, Text)] -> Link uri
forall uri. uri -> [(LinkParam, Text)] -> Link uri
Link uri
x [(LinkParam, Text)]
r) (Maybe uri -> Maybe (Link uri)) -> Maybe uri -> Maybe (Link uri)
forall a b. (a -> b) -> a -> b
$ Either String uri -> Maybe uri
forall a b. Either a b -> Maybe b
hush (Either String uri -> Maybe uri) -> Either String uri -> Maybe uri
forall a b. (a -> b) -> a -> b
$ Text -> Either String uri
forall uri. IsURI uri => Text -> Either String uri
uriFromText (Text -> Either String uri) -> Text -> Either String uri
forall a b. (a -> b) -> a -> b
$ String -> Text
pack String
u