module Handler.Utils.Minio
  ( MinioRunner(..)
  , getMinioRunner
  , runAppMinio
  , minioIsDoesNotExist
  ) where

import Import.NoFoundation
import Foundation.Type

import Network.Minio (Minio)
import qualified Network.Minio as Minio


newtype MinioRunner = MinioRunner
  { runMinio :: forall m' a. (MonadHandler m', HandlerSite m' ~ UniWorX, MonadThrow m') => Minio a -> m' a
  }
  
getMinioRunner :: (MonadHandler m, HandlerSite m ~ UniWorX)
               => m (Maybe MinioRunner)
getMinioRunner = runMaybeT $ do
  conn <- hoistMaybe =<< getsYesod appUploadCache
  return MinioRunner{ runMinio = throwLeft <=< liftIO . Minio.runMinioWith conn }
  
runAppMinio :: ( MonadHandler m, HandlerSite m ~ UniWorX
               , MonadThrow m
               , MonadPlus m
               )
            => Minio a -> m a
runAppMinio act = do
  MinioRunner{..} <- hoistMaybe =<< getMinioRunner
  runMinio act

minioIsDoesNotExist :: HttpException -> Bool
minioIsDoesNotExist (HttpExceptionRequest _ (StatusCodeException resp _))
  = responseStatus resp == notFound404
minioIsDoesNotExist _ = False
