-- SPDX-FileCopyrightText: 2022-2024 Gregor Kleen <gregor.kleen@ifi.lmu.de>, Steffen Jost <s.jost@fraport.de>
--
-- SPDX-License-Identifier: AGPL-3.0-or-later

module Utils.Pandoc where


import Import.NoModel

import Data.Either (fromRight)
-- import qualified Data.Char          as Char
-- import qualified Data.Text as Text
-- import qualified Data.CaseInsensitive as CI
import Text.Blaze (toMarkup)
import Text.Blaze.Html.Renderer.Text (renderHtml)
import qualified Text.Pandoc as P


markdownToHtml :: Html  -> Either P.PandocError Html
markdownToHtml html  = P.runPure $ P.writeHtml5 htmlWriterOptions =<< P.readMarkdown markdownReaderOptions (toStrict $ renderHtml html)

htmlToPlainText :: Html -> Either P.PandocError Text
htmlToPlainText html = P.runPure $ P.writePlain htmlWriterOptions =<< P.readHtml     markdownReaderOptions (toStrict $ renderHtml html)

plainTextToHtml :: Text -> Html
plainTextToHtml text = fromRight (toMarkup text) $ P.runPure $
  P.writeHtml5 htmlWriterOptions =<< P.readMarkdown markdownReaderOptions text
  -- Line below does not work as intended, also see Handler.Utils.Pandoc.plaintextToMarkdownWith which uses this code
  -- where pandoc = P.Pandoc mempty [P.Plain [P.Str text]]

plainHtmlToHtml :: Text -> Html
plainHtmlToHtml text = fromRight (toMarkup text) $ P.runPure $
  P.writeHtml5 htmlWriterOptions =<< P.readHtml markdownReaderOptions text



htmlReaderOptions, markdownReaderOptions :: P.ReaderOptions
htmlReaderOptions = markdownReaderOptions
markdownReaderOptions = def
  { P.readerExtensions = P.pandocExtensions
      & P.enableExtension P.Ext_hard_line_breaks
      & P.enableExtension P.Ext_autolink_bare_uris
  , P.readerTabStop = 2
  }

markdownWriterOptions, htmlWriterOptions :: P.WriterOptions
markdownWriterOptions = def
  { P.writerExtensions = P.readerExtensions markdownReaderOptions
  , P.writerTabStop = P.readerTabStop markdownReaderOptions
  }
htmlWriterOptions = markdownWriterOptions