{-# LANGUAGE UnicodeSyntax #-}
{-# LANGUAGE OverloadedStrings #-}
--------------------------------------------------------------------------------
-- File   : Cmd
-- Author : Alejandro Gómez Londoño
-- Date   : Sat Jun 27 01:12:12 2015
-- Description : Main handler for api calls
--------------------------------------------------------------------------------
-- Change log :

--------------------------------------------------------------------------------

module MonadBox.Cmd where

import MonadBox.Parser (Cmd(..))
import MonadBox.Types (DBMeta(..),Token)
import Data.Text (append,pack)
import Control.Lens ((&), (.~), (^.), (?~))
import Network.Wreq (auth,basicAuth,defaults
                    ,getWith,responseBody,oauth2Bearer
                    ,statusCode)
import Network.HTTP.Client (HttpException(StatusCodeException))
import Data.Text.Encoding (encodeUtf8)
import MonadBox.Util (asJSON)
import Control.Exception as E (catch)
import qualified MonadBox.URI as URI

doCommand ∷ Token → Cmd → IO ()
doCommand token (List Nothing)     = _DBMeta ""   token >>= print
doCommand token (List (Just path)) = _DBMeta path token >>= print
doCommand token _                  = undefined

_DBMeta ∷ String → Token → IO DBMeta
_DBMeta path token = catch request errorHandler
    where request = do
            let opts = defaults & auth ?~ oauth2Bearer (encodeUtf8 token)
            r ← asJSON =<< getWith opts (URI.metadata ++ path)
            return $ r ^. responseBody
          errorHandler (StatusCodeException s h _) =
              case s ^. statusCode of
                404  → return . MetaError $ "No such file or directory =("
                n    → return . MetaError $ "Unknown Error (#: " ++ (show n)
