aboutsummaryrefslogtreecommitdiff
path: root/Data/ConfigManager/Parser/Duration.hs
blob: f169c55407469d9e0ec3387701cf0c888e2fe165 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
{-# LANGUAGE OverloadedStrings #-}

module Data.ConfigManager.Parser.Duration
  ( parseDuration
  ) where

import Control.Applicative ((<|>))

import Data.Text (Text)
import qualified Data.Text as T
import Data.Time.Clock (DiffTime)
import qualified Data.Time.Clock as Time

import Text.Read (readMaybe)

parseDuration :: Text -> Maybe DiffTime
parseDuration input =
  case T.splitOn " " input of
    [count, unit] -> do
      n <- readMaybe . T.unpack $ count
      let matchDuration singularUnit pluralUnit seconds =
            if ((n == 0 || n == 1) && unit == singularUnit) || (n > 1 && unit == pluralUnit)
              then Just . Time.secondsToDiffTime $ n * seconds
              else Nothing
      (matchDuration "second" "seconds" second)
        <|> (matchDuration "minute" "minutes" minute)
        <|> (matchDuration "hour" "hours" hour)
        <|> (matchDuration "day" "days" day)
        <|> (matchDuration "week" "weeks" week)
    _ -> Nothing
  where
    second = 1
    minute = 60 * second
    hour = 60 * minute
    day = 24 * hour
    week = 7 * day