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

module Data.NonNull.Instances
  (
  ) where

import ClassyPrelude

import Data.Aeson

import Data.Binary (Binary)
import qualified Data.Binary as Binary

import Control.Monad.Fail

import Data.Swagger.Schema (ToSchema(..))

import Data.Proxy

import Servant.Docs
  

instance ToJSON a => ToJSON (NonNull a) where
  toJSON = toJSON . toNullable

instance (FromJSON a, MonoFoldable a) => FromJSON (NonNull a) where
  parseJSON = parseJSON >=> maybe (fail "Expected non-empty structure") return . fromNullable

instance ToSchema a => ToSchema (NonNull a) where
  declareNamedSchema _ = declareNamedSchema $ Proxy @a

instance (ToSample a, MonoFoldable a) => ToSample (NonNull a) where
  toSamples _ = do
    (l, s) <- toSamples (Proxy @a)
    s' <- maybe mzero pure $ fromNullable s
    return (l, s')


instance Hashable a => Hashable (NonNull a) where
  hashWithSalt s = hashWithSalt s . toNullable


instance (Binary a, MonoFoldable a) => Binary (NonNull a) where
  get = Binary.get >>= maybe (fail "Expected non-empty structure") return . fromNullable
  put = Binary.put . toNullable


instance NFData a => NFData (NonNull a) where
  rnf = rnf . toNullable
