{-# LANGUAGE DeriveLift #-}

-- | External file 'Asset's.
module Drasil.Assets.Core
  ( -- * Assets
    Asset,

    -- ** Constructors
    mkAsset,

    -- ** Accessors
    content,
    description,

    -- ** File Dumping
    toFile,
  )
where

import Data.ByteString qualified as B (ByteString)
import Data.Text (Text)
import Language.Haskell.TH.Syntax (Lift)
import Prelude hiding (readFile)

import Drasil.FileHandling (FileLayout, PathSegment, exactFile)

-- | An arbitrary file asset; a 'B.ByteString' with a description.
data Asset = Asset Text B.ByteString
  deriving ((forall (m :: * -> *). Quote m => Asset -> m Exp)
-> (forall (m :: * -> *). Quote m => Asset -> Code m Asset)
-> Lift Asset
forall t.
(forall (m :: * -> *). Quote m => t -> m Exp)
-> (forall (m :: * -> *). Quote m => t -> Code m t) -> Lift t
forall (m :: * -> *). Quote m => Asset -> m Exp
forall (m :: * -> *). Quote m => Asset -> Code m Asset
$clift :: forall (m :: * -> *). Quote m => Asset -> m Exp
lift :: forall (m :: * -> *). Quote m => Asset -> m Exp
$cliftTyped :: forall (m :: * -> *). Quote m => Asset -> Code m Asset
liftTyped :: forall (m :: * -> *). Quote m => Asset -> Code m Asset
Lift)

-- | Get the description of an 'Asset'.
description :: Asset -> Text
description :: Asset -> Text
description (Asset Text
desc ByteString
_) = Text
desc

-- | Get the raw 'ByteString' content of an 'Asset'.
content :: Asset -> B.ByteString
content :: Asset -> ByteString
content (Asset Text
_ ByteString
c) = ByteString
c

mkAsset :: Text -> B.ByteString -> Asset
mkAsset :: Text -> ByteString -> Asset
mkAsset = Text -> ByteString -> Asset
Asset

-- | Convert an 'Asset' to a 'FileLayout' node given a 'PathSegment' (file name)
-- it is to be written to.
toFile :: Asset -> PathSegment -> FileLayout
toFile :: Asset -> PathSegment -> FileLayout
toFile Asset
a = (PathSegment -> ByteString -> FileLayout)
-> ByteString -> PathSegment -> FileLayout
forall a b c. (a -> b -> c) -> b -> a -> c
flip PathSegment -> ByteString -> FileLayout
forall doc. Writeable doc => PathSegment -> doc -> FileLayout
exactFile (Asset -> ByteString
content Asset
a)