-- SPDX-FileCopyrightText: 2022 Gregor Kleen <gregor.kleen@ifi.lmu.de>,Sarah Vaupel <vaupel.sarah@campus.lmu.de>
--
-- SPDX-License-Identifier: AGPL-3.0-or-later

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

module Data.Fixed.Instances
  (
  ) where

import ClassyPrelude
import Data.Fixed

import Text.Blaze (ToMarkup(..))

import qualified Data.Csv as Csv
import Web.PathPieces

import Data.Proxy (Proxy(..))

import Data.Scientific
import Data.Scientific.Instances ()


instance HasResolution a => ToMarkup (Fixed a) where
  toMarkup = toMarkup . showFixed True


instance HasResolution a => Csv.ToField (Fixed a) where
  toField = Csv.toField . (realToFrac :: Fixed a -> Scientific)
instance HasResolution a => Csv.FromField (Fixed a) where
  parseField = fmap (MkFixed . (round :: Scientific -> Integer) . (* fromInteger (resolution $ Proxy @a))) . Csv.parseField

instance HasResolution a => PathPiece (Fixed a) where
  toPathPiece = toPathPiece . (realToFrac :: Fixed a -> Scientific)
  fromPathPiece = fmap (MkFixed . (round :: Scientific -> Integer) . (* fromInteger (resolution $ Proxy @a))) . fromPathPiece
