{-# OPTIONS_GHC -fno-warn-orphans #-}
module Net.IP.Instances
  (
  ) where

import ClassyPrelude

import Net.IP (IP)
import qualified Net.IP as IP

import Database.Persist.Sql

import qualified Data.Text.Encoding as Text


instance PersistField IP where
  toPersistValue = PersistDbSpecific . encodeUtf8 . IP.encode
  fromPersistValue (PersistDbSpecific bs) = first tshow (Text.decodeUtf8' bs) >>= maybe (Left "Could not parse IP-address") Right . IP.decode
  fromPersistValue (PersistByteString bs) = first tshow (Text.decodeUtf8' bs) >>= maybe (Left "Could not parse IP-address") Right . IP.decode
  fromPersistValue (PersistText t) = maybe (Left "Could not parse IP-address") Right $ IP.decode t
  fromPersistValue _ = Left "IP-address values must be converted from PersistDbSpecific, PersistText, or PersistByteString"
instance PersistFieldSql IP where
  sqlType _ = SqlOther "inet"
