module Dingo.Internal.Html
       ( mkHeadMerge
       ) where

import           Data.ByteString (ByteString)
import           Data.Maybe (mapMaybe)
import           Data.Monoid (Monoid(..))
import           Data.Text (Text, isSuffixOf)
import qualified Data.Text as T
import           Dingo.Internal.ResourceBundle.Internal (ResourceBundle, getResourceBundleContents)
import           Text.Blaze ((!), toValue)
import qualified Text.Blaze.Html4.Strict as H4
import qualified Text.Blaze.Html4.Strict.Attributes as A

-- Build head merge HTML content from a resource bundle.
mkHeadMerge :: ResourceBundle -> [H4.Html]
mkHeadMerge resourceBundle =
  mapMaybe headMerge directory
  where
    (guid, directory) = getResourceBundleContents resourceBundle

    path filePath = T.concat [ bundleRootUri, filePath ]

    bundleRootUri =
      T.concat ["/bundles/", guid, "/" ]

    headMerge :: (Text,ByteString) -> Maybe H4.Html
    headMerge (filePath, _) | ".css" `isSuffixOf` filePath =
      Just $ H4.link ! A.type_ "text/css" ! A.href (toValue $ path filePath) ! A.rel "stylesheet"
    headMerge (filePath, _) | ".js" `isSuffixOf` filePath =
      Just $ H4.script ! A.type_ "text/javascript" ! A.src (toValue $ path filePath) $ mempty
    headMerge (_,_) =
      mempty