module Websave.Web.Handlers
  ( getApiR
  ) where

import Data.Aeson (Encoding, Value (Object), eitherDecodeStrict)
import Data.Aeson.Types (parseEither, typeMismatch)
import Data.Maybe (fromMaybe)
import Data.Text (pack)
import Jsonine (getTag)
import Websave.Web.Api (api)
import Websave.Web.Data (getData)
import Websave.Web.Errors
  (DataNotFoundError (..), DecodeError (..), HandlerNotFoundError (..), ParseError (..), TagNotFoundError (..))
import Websave.Web.Routes (Handler)
import Yesod.Core.Json (returnJsonEncoding)

-- TODO extract method, move to WebTools (reimplement returnJsonEncoding to exclude Yesod dep)

getApiR :: Handler Encoding
getApiR = do
  d' <- getData
  case d' of
    Nothing -> returnJsonEncoding DataNotFoundError
    Just d ->
      case eitherDecodeStrict d of
        Left e -> returnJsonEncoding $ DecodeError $ pack e
        Right v ->
          case v of
            Object o ->
              case getTag o of
                Nothing -> returnJsonEncoding TagNotFoundError
                Just t ->
                  case lookup t api of
                    Nothing -> returnJsonEncoding HandlerNotFoundError
                    Just f -> f o
            _ ->
              returnJsonEncoding $ ParseError $ either pack undefined $ flip parseEither v $ typeMismatch "Object"
