module Network.API.TheMovieDB.Internal.Date
( Date (..),
parseDay,
(.::),
)
where
import Data.Aeson
import Data.Aeson.Types (Parser, typeMismatch)
import qualified Data.Text as Text
import Data.Time (Day (..), parseTimeM)
import Data.Time.Format (defaultTimeLocale)
newtype Date = Date {Date -> Maybe Day
day :: Maybe Day} deriving (Date -> Date -> Bool
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
/= :: Date -> Date -> Bool
$c/= :: Date -> Date -> Bool
== :: Date -> Date -> Bool
$c== :: Date -> Date -> Bool
Eq, Int -> Date -> ShowS
[Date] -> ShowS
Date -> String
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
showList :: [Date] -> ShowS
$cshowList :: [Date] -> ShowS
show :: Date -> String
$cshow :: Date -> String
showsPrec :: Int -> Date -> ShowS
$cshowsPrec :: Int -> Date -> ShowS
Show)
parseDay :: Object -> Key -> Parser (Maybe Day)
parseDay :: Object -> Key -> Parser (Maybe Day)
parseDay Object
v Key
key = do
Maybe Date
m <- Parser (Maybe Date)
date
forall (m :: * -> *) a. Monad m => a -> m a
return (Maybe Date
m forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Date -> Maybe Day
day)
where
date :: Parser (Maybe Date)
date :: Parser (Maybe Date)
date = Object
v forall a. FromJSON a => Object -> Key -> Parser (Maybe a)
.:? Key
key forall (f :: * -> *) a. Alternative f => f a -> f a -> f a
<|> forall (f :: * -> *) a. Applicative f => a -> f a
pure forall a. Maybe a
Nothing
(.::) :: Object -> Key -> Parser (Maybe Day)
.:: :: Object -> Key -> Parser (Maybe Day)
(.::) = Object -> Key -> Parser (Maybe Day)
parseDay
instance FromJSON Date where
parseJSON :: Value -> Parser Date
parseJSON Value
Null = forall (m :: * -> *) a. Monad m => a -> m a
return (Maybe Day -> Date
Date forall a. Maybe a
Nothing)
parseJSON (String Text
t)
| Text -> Bool
Text.null Text
t = forall (m :: * -> *) a. Monad m => a -> m a
return (Maybe Day -> Date
Date forall a. Maybe a
Nothing)
| Bool
otherwise = do
Day
d <- forall (m :: * -> *) t.
(MonadFail m, ParseTime t) =>
Bool -> TimeLocale -> String -> String -> m t
parseTimeM Bool
True TimeLocale
defaultTimeLocale String
"%Y-%m-%d" (forall a. ToString a => a -> String
toString Text
t)
forall (m :: * -> *) a. Monad m => a -> m a
return forall a b. (a -> b) -> a -> b
$ Maybe Day -> Date
Date (forall a. a -> Maybe a
Just Day
d)
parseJSON Value
v = forall a. String -> Value -> Parser a
typeMismatch String
"Date" Value
v