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

module Data.Time.Clock.Instances
  () where

import ClassyPrelude

import Database.Persist.Sql

import Data.Proxy

import Data.Time.Clock
import Data.Time.Calendar.Instances ()
import Web.PathPieces

import qualified Data.Csv as Csv

import Data.Time.Format.ISO8601


instance Hashable DiffTime where
  hashWithSalt s = hashWithSalt s . toRational

instance Hashable NominalDiffTime where
  hashWithSalt s = hashWithSalt s . toRational

instance PersistField NominalDiffTime where
  toPersistValue   = toPersistValue . toRational
  fromPersistValue = fmap fromRational . fromPersistValue

instance PersistFieldSql NominalDiffTime where
  sqlType _ = sqlType (Proxy @Rational)


deriving instance Generic UTCTime
instance Hashable UTCTime

instance PathPiece UTCTime where
  toPathPiece = pack . iso8601Show
  fromPathPiece = iso8601ParseM . unpack

instance Csv.ToField UTCTime where
  toField = Csv.toField . iso8601Show

instance Csv.FromField UTCTime where
  parseField = iso8601ParseM <=< Csv.parseField
