{-# LANGUAGE OverloadedStrings #-}

module Text.Hastily.MovieInfoSources.Omdb.Omdb
    (
     getMovieInfo,
     OMDBSearchResult(OMDBSearchResult)
    ) where

import           Data.Aeson
import           Data.ByteString.Char8 hiding (putStrLn)
import qualified Data.ByteString.Lazy    as LZ
import           Data.String.Conversions
import           Data.Text               (Text)
import           Network.HTTP.Client
import           Control.Applicative
import           Data.Functor

import           Text.Hastily.Network
import           Text.Hastily.Types
import           Control.Exception

--sampleJSON = cs $ pack "{\"Search\":[{\"Title\":\"Ferris Bueller's Day Off\",\"Year\":\"1986\",\"imdbID\":\"tt0091042\",\"Type\":\"movie\"},{\"Title\":\"Ferris Bueller\",\"Year\":\"1990–1991\",\"imdbID\":\"tt0098795\",\"Type\":\"series\"},{\"Title\":\"The Night Ferris Bueller Died\",\"Year\":\"1999\",\"imdbID\":\"tt0240760\",\"Type\":\"movie\"},{\"Title\":\"Inside Story: Ferris Bueller's Day Off\",\"Year\":\"2011\",\"imdbID\":\"tt2150301\",\"Type\":\"movie\"},{\"Title\":\"The Ferris Wheel\",\"Year\":\"1896\",\"imdbID\":\"tt2207641\",\"Type\":\"movie\"},{\"Title\":\"Farewell, Ferris Wheel\",\"Year\":\"2012\",\"imdbID\":\"tt2349677\",\"Type\":\"movie\"},{\"Title\":\"Ferris Wheel at Night\",\"Year\":\"2013\",\"imdbID\":\"tt2496624\",\"Type\":\"movie\"},{\"Title\":\"Ferris Wheel on Fire\",\"Year\":\"2010\",\"imdbID\":\"tt2991876\",\"Type\":\"movie\"},{\"Title\":\"Brad Ferris' Game Plan\",\"Year\":\"2013–\",\"imdbID\":\"tt3464692\",\"Type\":\"series\"},{\"Title\":\"When the Ferris Wheel Stops\",\"Year\":\"2015\",\"imdbID\":\"tt4158616\",\"Type\":\"movie\"}]}"

data OMDBSearchResult = OMDBSearchResult [MovieInfo] deriving (Show)

instance FromJSON OMDBSearchResult where
    parseJSON (Object v) = OMDBSearchResult <$> v .: "Search"

getMovieInfo :: Text -> IO (Either SomeException OMDBSearchResult)
getMovieInfo slug = do
    either_response_body <- getFrom "http://www.omdbapi.com" [("r", "json"), ("s", slug)]
    case either_response_body of
        Left err -> do
            putStrLn "Querying OMDB for movie details failed!"
            return $ Left err
        Right response_body -> case eitherDecode response_body::Either String OMDBSearchResult of
            Left err -> error $ "Your search for '" <> (cs slug) <> "' did not yield any results!"
            Right result -> return $ Right result