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

module Network.IP.Addr.Instances
  (
  ) where


import ClassyPrelude

import Network.IP.Addr
import qualified Data.Textual as Textual

import Database.Persist.Sql

import qualified Data.Text.Encoding as Text

import Utils.Persist
import Data.Proxy


instance PersistField IP where
  toPersistValue = PersistLiteralEscaped . Textual.toUtf8
  fromPersistValue (PersistLiteralEscaped bs) = first tshow (Text.decodeUtf8' bs) >>= maybe (Left "Could not parse IP-address") Right . Textual.fromText
  fromPersistValue (PersistByteString bs) = first tshow (Text.decodeUtf8' bs) >>= maybe (Left "Could not parse IP-address") Right . Textual.fromText
  fromPersistValue (PersistText t) = maybe (Left "Could not parse IP-address") Right $ Textual.fromText t
  fromPersistValue x = Left $ fromPersistValueErrorSql (Proxy @IP) x
instance PersistFieldSql IP where
  sqlType _ = SqlOther "inet"


instance (NFData v4, NFData v6) => NFData (IP46 v4 v6) where
  rnf (IPv4 v4) = rnf v4
  rnf (IPv6 v6) = rnf v6

instance NFData IP4 where
  rnf = rnf . ip4ToOctets

instance NFData IP6 where
  rnf = rnf . ip6ToWords
