-- | Internal module.
--
-- @since 0.1
module Kairos.Internal
  ( -- * TZ Database Labels
    tzNameToTZLabel,
    tzLowerNameLabelMap,
    tzLowerNameLabelMapWith,
  )
where

import Data.Map.Strict (Map)
import Data.Map.Strict qualified as Map
import Data.Text (Text)
import Data.Text qualified as T
import Data.Text.Encoding qualified as TEnc
import Data.Text.Encoding.Error (OnDecodeError)
import Data.Text.Encoding.Error qualified as TError
import Data.Time.Zones.All (TZLabel)
import Data.Time.Zones.All qualified as All

-- | Looks up a tz database label by name. Case-insensitive.
--
-- @since 0.1
tzNameToTZLabel :: Text -> Maybe TZLabel
tzNameToTZLabel :: Text -> Maybe TZLabel
tzNameToTZLabel = (Text -> Map Text TZLabel -> Maybe TZLabel
forall k a. Ord k => k -> Map k a -> Maybe a
`Map.lookup` Map Text TZLabel
tzLowerNameLabelMap) (Text -> Maybe TZLabel) -> (Text -> Text) -> Text -> Maybe TZLabel
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> Text
T.toLower

-- | Like @tz@'s @tzNameLabelMap@ but with lower-case 'Text' keys instead of
-- ByteString for case-insensitive lookup.
--
-- @since 0.1
tzLowerNameLabelMap :: Map Text TZLabel
tzLowerNameLabelMap :: Map Text TZLabel
tzLowerNameLabelMap = OnDecodeError -> Map Text TZLabel
tzLowerNameLabelMapWith OnDecodeError
TError.lenientDecode

-- | tzLowerNameLabelMapOnError with custom decoder, since we need to convert
-- ByteString -> Text.
--
-- @since 0.1
tzLowerNameLabelMapWith :: OnDecodeError -> Map Text TZLabel
tzLowerNameLabelMapWith :: OnDecodeError -> Map Text TZLabel
tzLowerNameLabelMapWith OnDecodeError
decoder = (ByteString -> Text) -> Map ByteString TZLabel -> Map Text TZLabel
forall k2 k1 a. Ord k2 => (k1 -> k2) -> Map k1 a -> Map k2 a
Map.mapKeys ByteString -> Text
toLower Map ByteString TZLabel
All.tzNameLabelMap
  where
    toLower :: ByteString -> Text
toLower = Text -> Text
T.toLower (Text -> Text) -> (ByteString -> Text) -> ByteString -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. OnDecodeError -> ByteString -> Text
TEnc.decodeUtf8With OnDecodeError
decoder