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

module Network.URI.Instances
  (
  ) where

import ClassyPrelude
import Network.URI
import qualified Data.Aeson as Aeson

import Control.Monad.Fail (MonadFail(..))

import Database.Persist
import Database.Persist.Sql


instance Aeson.ToJSON URI where
  toJSON = Aeson.String . pack . ($ mempty) . uriToString id
instance Aeson.FromJSON URI where
  parseJSON = Aeson.withText "URI" $ maybe (fail "Could not parse URI") return . parseURIReference . unpack

instance PersistField URI where
  toPersistValue = PersistText . pack . ($ mempty) . uriToString id 
  fromPersistValue (PersistText t) = maybe (Left "Could not parse URI") return . parseURIReference $ unpack t
  fromPersistValue v = Left $ "Failed to parse Haskell type `URI`; expected text from database but received: " <> tshow v <> "."
instance PersistFieldSql URI where
  sqlType _ = SqlString
