module FFProbe.Internal (parseReadable, parseOptionalValue) where

import Data.Aeson.Types (Parser)
import Text.Read (readMaybe)

-- | applies `readMaybe` to a value, and turns the result into a Parser
parseReadable :: (Read a) => String -> Parser a
parseReadable :: forall a. Read a => String -> Parser a
parseReadable String
n = case String -> Maybe a
forall a. Read a => String -> Maybe a
readMaybe String
n of
    Maybe a
Nothing -> String -> Parser a
forall a. String -> Parser a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail String
"Failed to read value"
    Just a
x -> a -> Parser a
forall a. a -> Parser a
forall (f :: * -> *) a. Applicative f => a -> f a
pure a
x

-- | applies `readMaybe` to a value, and turns the result into a Parser
parseOptionalValue :: (Read a) => Maybe String -> Parser (Maybe a)
parseOptionalValue :: forall a. Read a => Maybe String -> Parser (Maybe a)
parseOptionalValue Maybe String
Nothing = Maybe a -> Parser (Maybe a)
forall a. a -> Parser a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Maybe a
forall a. Maybe a
Nothing
parseOptionalValue (Just String
v) = a -> Maybe a
forall a. a -> Maybe a
Just (a -> Maybe a) -> Parser a -> Parser (Maybe a)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> String -> Parser a
forall a. Read a => String -> Parser a
parseReadable String
v