module Jerimum.PostgreSQL.Types.DateRange
    -- * CBOR codec
  ( dateRangeEncoderV0
  , dateRangeDecoderV0
  , encodeDateRange
    -- * Text codec
  , parseDateRange
  , formatDateRange
    -- * Value constructors
  , fromDateRange
  ) where

import qualified Codec.CBOR.Decoding               as D
import qualified Codec.CBOR.Encoding               as E
import qualified Data.Attoparsec.Text              as A
import qualified Data.Text                         as T
import           Data.Text.Lazy                    (toStrict)
import           Data.Text.Lazy.Builder
import           Jerimum.PostgreSQL.Types
import           Jerimum.PostgreSQL.Types.DateTime
import           Jerimum.PostgreSQL.Types.Encoding

v0 :: Version
v0 = 0

encodeDateRange :: Maybe (Range Day) -> E.Encoding
encodeDateRange = encodeWithVersion v0 dateRangeEncoderV0

dateRangeParser :: A.Parser (Range Day)
dateRangeParser = rangeParser (Scalar <$> dateParser)

parseDateRange :: T.Text -> Maybe (Range Day)
parseDateRange = runParser "parseDateRange: parse error" dateRangeParser

formatDateRange :: Range Day -> T.Text
formatDateRange = toStrict . toLazyText . buildRange buildDate

fromDateRange :: Maybe (Range Day) -> Value
fromDateRange = mkValue (RangeType TDate) encodeDateRange

dateRangeEncoderV0 :: Range Day -> E.Encoding
dateRangeEncoderV0 = rangeEncoderV0 dateEncoderV0

dateRangeDecoderV0 :: D.Decoder s (Range Day)
dateRangeDecoderV0 = rangeDecoderV0 dateDecoderV0
