module Network.IPFS.Remote.Class
  ( MonadRemoteIPFS
  , runRemote
  , ipfsAdd
  , ipfsCat
  , ipfsStat
  , ipfsPin
  , ipfsUnpin
  ) where

import           Network.IPFS.Prelude

import qualified RIO.ByteString.Lazy       as Lazy
import           Servant.Client

import           Network.IPFS.Types        as IPFS

import qualified Network.IPFS.Client       as IPFS.Client
import qualified Network.IPFS.Client.Pin   as Pin
import qualified Network.IPFS.File.Types   as File

import           Network.IPFS.Remote.Error

class MonadIO m => MonadRemoteIPFS m where
  runRemote :: ClientM a       -> m (Either ClientError a)
  ipfsAdd   :: Lazy.ByteString -> m (Either ClientError CID)
  ipfsCat   :: CID             -> m (Either ClientError File.Serialized)
  ipfsStat  :: CID             -> m (Either StatError   Stat)
  ipfsPin   :: CID             -> m (Either ClientError Pin.Response)
  ipfsUnpin :: CID -> Bool     -> m (Either ClientError Pin.Response)

  -- defaults
  ipfsAdd   ByteString
raw           = forall (m :: * -> *) a.
MonadRemoteIPFS m =>
ClientM a -> m (Either ClientError a)
runRemote forall a b. (a -> b) -> a -> b
$ ByteString -> ClientM CID
IPFS.Client.add ByteString
raw
  ipfsCat   CID
cid           = forall (m :: * -> *) a.
MonadRemoteIPFS m =>
ClientM a -> m (Either ClientError a)
runRemote forall a b. (a -> b) -> a -> b
$ CID -> ClientM Serialized
IPFS.Client.cat   CID
cid
  ipfsPin   CID
cid           = forall (m :: * -> *) a.
MonadRemoteIPFS m =>
ClientM a -> m (Either ClientError a)
runRemote forall a b. (a -> b) -> a -> b
$ CID -> ClientM Response
IPFS.Client.pin   CID
cid
  ipfsUnpin CID
cid Bool
recursive = forall (m :: * -> *) a.
MonadRemoteIPFS m =>
ClientM a -> m (Either ClientError a)
runRemote forall a b. (a -> b) -> a -> b
$ CID -> Bool -> ClientM Response
IPFS.Client.unpin CID
cid Bool
recursive

  ipfsStat CID
cid =
    forall (m :: * -> *) a.
MonadRemoteIPFS m =>
ClientM a -> m (Either ClientError a)
runRemote (CID -> ClientM (Either OverflowDetected Stat)
IPFS.Client.stat  CID
cid) forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \case
      Left  ClientError
clientErr       -> forall (m :: * -> *) a. Monad m => a -> m a
return forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a b. a -> Either a b
Left forall a b. (a -> b) -> a -> b
$ ClientError -> StatError
WebError  ClientError
clientErr
      Right (Left OverflowDetected
sizeErr)  -> forall (m :: * -> *) a. Monad m => a -> m a
return forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a b. a -> Either a b
Left forall a b. (a -> b) -> a -> b
$ OverflowDetected -> StatError
SizeError OverflowDetected
sizeErr
      Right (Right Stat
payload) -> forall (m :: * -> *) a. Monad m => a -> m a
return forall a b. (a -> b) -> a -> b
$ forall a b. b -> Either a b
Right Stat
payload