{- This file is part of Vervis.
 -
 - Written in 2019 by fr33domlover <fr33domlover@riseup.net>.
 -
 - ♡ Copying is an act of love. Please copy, reuse and share.
 -
 - The author(s) have dedicated all copyright and related and neighboring
 - rights to this software to the public domain worldwide. This software is
 - distributed without any warranty.
 -
 - You should have received a copy of the CC0 Public Domain Dedication along
 - with this software. If not, see
 - <http://creativecommons.org/publicdomain/zero/1.0/>.
 -}

-- | A replacement for "Data.Aeson.Encode.Pretty" which uses 'toEncoding'
-- instead of 'toJSON'.
module Data.Aeson.Encode.Pretty.ToEncoding
    ( encodePretty
    , encodePrettyToLazyText
    , encodePrettyToTextBuilder
    )
where

import Prelude

import Data.Aeson (ToJSON, Value, encode, decode)
import Data.ByteString.Lazy (ByteString)
import Data.Maybe (fromJust)
import Data.Text.Lazy (Text)
import Data.Text.Lazy.Builder (Builder, fromLazyText)
import Data.Text.Lazy.Encoding (decodeUtf8)

import qualified Data.Aeson.Encode.Pretty as P (encodePretty)

encodePretty :: ToJSON a => a -> ByteString
encodePretty = P.encodePretty . fromJust . decodeValue . encode
    where
    decodeValue :: ByteString -> Maybe Value
    decodeValue = decode

encodePrettyToLazyText :: ToJSON a => a -> Text
encodePrettyToLazyText = decodeUtf8 . encodePretty

encodePrettyToTextBuilder :: ToJSON a => a -> Builder
encodePrettyToTextBuilder = fromLazyText . encodePrettyToLazyText