{-# LANGUAGE OverloadedStrings #-}
module Main (main) where

import Control.Monad (unless)
import qualified Data.Text as T
import Text.HTML.TagSoup (Tag(..), parseTags)
import Text.Pandoc
import Text.Pandoc.Walk (query)
import Utils (balancedHTMLFragment, isHTMLVoidTag, parseRawAllClean,
              parseRawAllCleanAndInline, safeHtmlWriterOptions, toMarkdownFromHTML, wrapInParagraphs)

assert :: String -> Bool -> IO ()
assert label ok = unless ok $ error label

parse :: T.Text -> Pandoc
parse = either (error . show) id . runPure . readMarkdown def{readerExtensions=pandocExtensions}

render :: Pandoc -> T.Text
render = either (error . show) id . runPure . writeHtml5String safeHtmlWriterOptions

compile :: T.Text -> T.Text
compile = render . wrapInParagraphs . parseRawAllClean . parse

count :: String -> [Tag String] -> Int
count tag = length . filter (== TagClose tag)

main :: IO ()
main = do
  assert "void names are case insensitive" (all isHTMLVoidTag ["col", "IMG", "source", "wbr"])
  assert "ordinary elements aren't void" (not $ isHTMLVoidTag "figure")
  assert "balanced fragment with void child" (balancedHTMLFragment "<figure><IMG src='x'><figcaption>Caption</figcaption></figure>")
  assert "XHTML void elements are balanced" (balancedHTMLFragment "<p>a<br />b<img src=\"x\" /></p>")
  assert "split figure opener is partial" (not $ balancedHTMLFragment "<figure>")
  assert "split figure closer is partial" (not $ balancedHTMLFragment "</figure>")
  assert "crossed tags are partial" (not $ balancedHTMLFragment "<a><em>x</a></em>")
  assert "comments do not affect balance" (balancedHTMLFragment "<!-- <figure> --><p>x</p>")

  let figure = "<figure class=\"float-right\">\n<img src=\"/cat.jpg\">\n<figcaption>Cat caption</figcaption>\n</figure>"
      figureHTML = compile figure
      figureTags = parseTags (T.unpack figureHTML)
  assert "one figure close after split raw blocks" (count "figure" figureTags == 1)
  assert "figure retains its caption and class" ("float-right" `T.isInfixOf` figureHTML && "Cat caption" `T.isInfixOf` figureHTML)
  assert "raw opener does not become an empty native figure" (not $ "<figure class=\"float-right\">\n\n</figure>" `T.isInfixOf` figureHTML)

  let paragraph = "<p class=\"dropcap-kanzlei\">\n[Long before]{.smallcaps}, I read [Space Age](!W).\n</p>"
      paragraphHTML = compile paragraph
  assert "explicit raw paragraph has one closing tag" (count "p" (parseTags $ T.unpack paragraphHTML) == 1)
  assert "explicit paragraph class survives" ("dropcap-kanzlei" `T.isInfixOf` paragraphHTML)
  assert "Markdown in explicit paragraph is still parsed" ("href=\"!W\"" `T.isInfixOf` paragraphHTML)
  assert "tight list becomes loose" ("<li><p>item</p></li>" `T.isInfixOf` compile "- item")
  assert "definition-list definitions become paragraphs" (wrapInParagraphs (Pandoc nullMeta [DefinitionList [([Str "term"], [[Plain [Str "meaning"]]])]]) == Pandoc nullMeta [DefinitionList [([Str "term"], [[Para [Str "meaning"]]])]])
  assert "native figure caption keeps its paragraph" ("<figcaption" `T.isInfixOf` compile "![Cat caption](/cat.jpg)" && "<p>Cat caption</p>" `T.isInfixOf` compile "![Cat caption](/cat.jpg)")
  let rawItem = Pandoc nullMeta [BulletList [[RawBlock (Format "html") "<p>", Plain [Str "item"], RawBlock (Format "html") "</p>"]]]
  assert "list item with explicit raw paragraph isn't nested" (wrapInParagraphs rawItem == rawItem)
  let boundary = Pandoc nullMeta [Para [RawInline (Format "html") "<sub>",Str "2",RawInline (Format "html") "</sub>"]]
  assert "inline structural boundaries survive" (parseRawAllCleanAndInline boundary == boundary)

  let body = "<p><a href=\"/q\">Q*</a> and Q* again.</p>\n<ol>\n  <li><p>First</p>\n    <p>Second paragraph.</p></li>\n  <li><p>Quote:</p>\n    <blockquote>\n      <p>Quoted words.</p>\n    </blockquote></li>\n</ol>\n<p><code class=\"sourceCode haskell\"><span class=\"dv\">3</span><span class=\"op\">+</span><span class=\"dv\">4</span></code></p>"
      blog = toMarkdownFromHTML body
      blogDoc = parse (T.pack blog)
      blogHTML = compile (T.pack blog)
      codeBlocks (CodeBlock _ _) = [True]
      codeBlocks _ = []
      inlineCodes (Code _ value) = [value]
      inlineCodes _ = []
  assert "GTX indentation does not become code" (null $ query codeBlocks blogDoc)
  assert "literal stars do not become emphasis" ("Q*</a> and Q* again." `T.isInfixOf` blogHTML)
  assert "nested quote is real blockquote" (count "blockquote" (parseTags $ T.unpack blogHTML) == 1)
  assert "highlighted inline code content survives" (T.concat (query inlineCodes blogDoc) == "3+4")
  putStrLn "HTML structure regression tests passed (23 checks)."
