{-# language FlexibleContexts    #-}
{-# language ScopedTypeVariables #-}
{-# language TypeApplications    #-}
{-# language TypeFamilies        #-}
{-# language TypeOperators       #-}
module Mu.Kafka.Internal where

import qualified Data.Avro            as A
import           Data.ByteString
import           Data.ByteString.Lazy (fromStrict, toStrict)

import           Mu.Schema

toBS :: forall sch sty t.
        ( ToSchema sch sty t
        , A.HasAvroSchema (WithSchema sch sty t)
        , A.ToAvro (WithSchema sch sty t) )
     => Proxy sch -> t -> ByteString
toBS :: Proxy sch -> t -> ByteString
toBS _ = ByteString -> ByteString
toStrict (ByteString -> ByteString) -> (t -> ByteString) -> t -> ByteString
forall b c a. (b -> c) -> (a -> b) -> a -> c
. WithSchema sch sty t -> ByteString
forall a. (HasAvroSchema a, ToAvro a) => a -> ByteString
A.encodeValue (WithSchema sch sty t -> ByteString)
-> (t -> WithSchema sch sty t) -> t -> ByteString
forall b c a. (b -> c) -> (a -> b) -> a -> c
. t -> WithSchema sch sty t
forall tn fn (sch :: Schema tn fn) (sty :: tn) a.
a -> WithSchema sch sty a
WithSchema @_ @_ @sch @sty @t

fromBS :: forall sch sty t.
          ( FromSchema sch sty t
          , A.FromAvro (WithSchema sch sty t)
          , A.HasAvroSchema (WithSchema sch sty t) )
       => Proxy sch -> ByteString -> Maybe t
fromBS :: Proxy sch -> ByteString -> Maybe t
fromBS _ x :: ByteString
x = WithSchema sch sty t -> t
forall tn fn (sch :: Schema tn fn) (sty :: tn) a.
WithSchema sch sty a -> a
unWithSchema @_ @_ @sch @sty @t (WithSchema sch sty t -> t)
-> Maybe (WithSchema sch sty t) -> Maybe t
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Either String (WithSchema sch sty t)
-> Maybe (WithSchema sch sty t)
forall a a. Either a a -> Maybe a
resultToMaybe (ByteString -> Either String (WithSchema sch sty t)
forall a.
(HasAvroSchema a, FromAvro a) =>
ByteString -> Either String a
A.decodeValue (ByteString -> ByteString
fromStrict ByteString
x))
  where
    resultToMaybe :: Either a a -> Maybe a
resultToMaybe (Left  _) = Maybe a
forall a. Maybe a
Nothing
    resultToMaybe (Right y :: a
y) = a -> Maybe a
forall a. a -> Maybe a
Just a
y