{-# OPTIONS_GHC -fno-warn-orphans #-}

module URI.ByteString.Aeson () where

import           Data.Aeson
import qualified Data.ByteString as BS
import           URI.ByteString
import           Data.Text.Encoding
import           Control.Monad

class ParseJSONURI a where
  parseJSONURI :: BS.ByteString -> Either URIParseError (URIRef a)

instance ParseJSONURI Absolute where
  parseJSONURI :: ByteString -> Either URIParseError (URIRef Absolute)
parseJSONURI = URIParserOptions
-> ByteString -> Either URIParseError (URIRef Absolute)
parseURI URIParserOptions
laxURIParserOptions

instance ParseJSONURI Relative where
  parseJSONURI :: ByteString -> Either URIParseError (URIRef Relative)
parseJSONURI = URIParserOptions
-> ByteString -> Either URIParseError (URIRef Relative)
parseRelativeRef URIParserOptions
laxURIParserOptions

instance ParseJSONURI a => FromJSON (URIRef a) where
  parseJSON :: Value -> Parser (URIRef a)
parseJSON = Value -> Parser Text
forall a. FromJSON a => Value -> Parser a
parseJSON (Value -> Parser Text)
-> (Text -> Parser (URIRef a)) -> Value -> Parser (URIRef a)
forall (m :: * -> *) a b c.
Monad m =>
(a -> m b) -> (b -> m c) -> a -> m c
>=> (URIParseError -> Parser (URIRef a))
-> (URIRef a -> Parser (URIRef a))
-> Either URIParseError (URIRef a)
-> Parser (URIRef a)
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (String -> Parser (URIRef a)
forall a. String -> Parser a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail (String -> Parser (URIRef a))
-> (URIParseError -> String) -> URIParseError -> Parser (URIRef a)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. URIParseError -> String
forall a. Show a => a -> String
show) URIRef a -> Parser (URIRef a)
forall a. a -> Parser a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Either URIParseError (URIRef a) -> Parser (URIRef a))
-> (Text -> Either URIParseError (URIRef a))
-> Text
-> Parser (URIRef a)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ByteString -> Either URIParseError (URIRef a)
forall a.
ParseJSONURI a =>
ByteString -> Either URIParseError (URIRef a)
parseJSONURI (ByteString -> Either URIParseError (URIRef a))
-> (Text -> ByteString) -> Text -> Either URIParseError (URIRef a)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> ByteString
encodeUtf8

instance ToJSON (URIRef f) where
  toJSON :: URIRef f -> Value
toJSON = Text -> Value
forall a. ToJSON a => a -> Value
toJSON (Text -> Value) -> (URIRef f -> Text) -> URIRef f -> Value
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ByteString -> Text
decodeUtf8 (ByteString -> Text)
-> (URIRef f -> ByteString) -> URIRef f -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. URIRef f -> ByteString
forall a. URIRef a -> ByteString
serializeURIRef'