-- | This module provides no own time type for taskwarrior rather it only gives deserialisation and serialisation support.
module Taskwarrior.Time (
  parse,
  toValue,
) where

import Data.Aeson (withText)
import qualified Data.Aeson as Aeson
import Data.Aeson.Types (
  Parser,
  typeMismatch,
 )
import qualified Data.Text as Text
import Data.Time (
  UTCTime,
  defaultTimeLocale,
  parseTimeM,
 )
import qualified Data.Time.Format as Time.Format

-- | Converts a time to the taskwarrior time format.
toValue :: UTCTime -> Aeson.Value
toValue :: UTCTime -> Value
toValue UTCTime
time =
  Text -> Value
Aeson.String forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> Text
Text.pack forall a b. (a -> b) -> a -> b
$
    forall t. FormatTime t => TimeLocale -> String -> t -> String
Time.Format.formatTime
      TimeLocale
defaultTimeLocale
      String
"%Y%m%dT%H%M%SZ"
      UTCTime
time

-- | Parses a JSON string from the taskwarrior time format.
parse :: Aeson.Value -> Parser UTCTime
parse :: Value -> Parser UTCTime
parse Value
value =
  forall a. String -> (Text -> Parser a) -> Value -> Parser a
withText
    String
"Date"
    ( forall b a. b -> (a -> b) -> Maybe a -> b
maybe (forall a. String -> Value -> Parser a
typeMismatch String
"Date" Value
value) forall (f :: * -> *) a. Applicative f => a -> f a
pure
        forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall (m :: * -> *) t.
(MonadFail m, ParseTime t) =>
Bool -> TimeLocale -> String -> String -> m t
parseTimeM Bool
False TimeLocale
defaultTimeLocale String
"%Y%m%dT%H%M%SZ"
        forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> String
Text.unpack
    )
    Value
value