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

module Data.CryptoID.Instances
  (
  ) where

import qualified Data.CryptoID as CID

import Text.Blaze (ToMarkup(..))

import ClassyPrelude

import Data.CaseInsensitive (CI)
import qualified Data.CaseInsensitive as CI

import Web.PathPieces
import Data.Aeson (ToJSON(..), ToJSONKey(..), ToJSONKeyFunction(..))

import qualified Data.Csv as Csv


instance ToMarkup s => ToMarkup (CID.CryptoID c s) where
  toMarkup = toMarkup . CID.ciphertext

instance {-# OVERLAPS #-} ToMarkup s => ToMarkup (CID.CryptoID c (CI s)) where
  toMarkup = toMarkup . CI.foldedCase . CID.ciphertext

instance {-# OVERLAPS #-} ToJSON s => ToJSON (CID.CryptoID c (CI s)) where
  toJSON = toJSON . CI.foldedCase . CID.ciphertext

instance {-# OVERLAPS #-} (ToJSON s, ToJSONKey s) => ToJSONKey (CID.CryptoID c (CI s)) where
  toJSONKey = case toJSONKey of
    ToJSONKeyText toT toE -> ToJSONKeyText (toT . CI.foldedCase . CID.ciphertext) (toE . CI.foldedCase . CID.ciphertext)
    ToJSONKeyValue toV toE -> ToJSONKeyValue (toV . CI.foldedCase . CID.ciphertext) (toE . CI.foldedCase . CID.ciphertext)

instance {-# OVERLAPS #-} (PathPiece s, CI.FoldCase s) => PathPiece (CID.CryptoID c (CI s)) where
  toPathPiece = toPathPiece . CI.foldedCase . CID.ciphertext
  fromPathPiece = fmap (CID.CryptoID . CI.mk) . fromPathPiece

instance Csv.FromField s => Csv.FromField (CID.CryptoID c s) where
  parseField = fmap CID.CryptoID . Csv.parseField

instance Csv.ToField s => Csv.ToField (CID.CryptoID c s) where
  toField = Csv.toField . CID.ciphertext

instance {-# OVERLAPS #-} Csv.ToField s => Csv.ToField (CID.CryptoID c (CI s)) where
  toField = Csv.toField . CI.foldedCase . CID.ciphertext
