-- Run from the static repository: runghc -ibuild build/test/ImageHTMLTest.hs
-- No image files, ImageMagick processes, or network requests are needed.
module Main where

import Control.Monad (forM_, unless)
import Data.Char (toUpper)
import Data.List (isInfixOf)
import System.Exit (exitFailure)

import Image (addImgDimensions)

assert :: String -> Bool -> IO ()
assert label ok = unless ok $ putStrLn ("FAIL: " ++ label) >> exitFailure

main :: IO ()
main = do
  -- Trigger the whole-document TagSoup path without looking up a local image.
  let image = "<img src=\"https://example.org/test.png\" />"
      voidTags = ["area", "base", "br", "col", "embed", "hr", "img", "input",
                  "link", "meta", "param", "source", "track", "wbr"]
  forM_ (voidTags ++ map (map toUpper) voidTags) $ \tag -> do
    let input = "<" ++ tag ++ " data-test=\"A &amp; B\" />" ++ image
    -- A second img needs a source attribute even though the first already triggers parsing.
        fixture = if tag == "img" then "<img src=\"https://example.org/second.png\" />" ++ image
                  else input
    output <- addImgDimensions fixture
    assert (tag ++ " has no forbidden end tag") $ not $ ("</" ++ tag ++ ">") `isInfixOf` output
    assert (tag ++ " survives") $ ("<" ++ tag ++ " ") `isInfixOf` output
    outputAgain <- addImgDimensions output
    assert (tag ++ " is stable on a second pass") $ outputAgain == output

  let table = "<table><colgroup><col style=\"width: 66%\" /><col style=\"width: 34%\" /></colgroup><tbody><tr><td>A</td><td>B</td></tr></tbody></table>"
  outputTable <- addImgDimensions $ table ++ image
  assert "Pandoc table keeps its columns" $ "<col style=\"width: 66%\" />" `isInfixOf` outputTable
  assert "Pandoc table has no col end tag" $ not $ "</col>" `isInfixOf` outputTable
  outputWithoutImage <- addImgDimensions table
  assert "image-free HTML is untouched" $ outputWithoutImage == table

  forM_ ["span", "div", "a", "script", "style", "textarea", "path", "mspace"] $ \tag -> do
    output <- addImgDimensions $ "<" ++ tag ++ "></" ++ tag ++ ">" ++ image
    assert (tag ++ " retains its required end tag") $ ("</" ++ tag ++ ">") `isInfixOf` output

  let raw = "<script>if (x < 1 && y > 2) alert(\"A&B\");</script><style>p::before { content: \"<&>\"; }</style>"
  outputRaw <- addImgDimensions $ raw ++ image
  assert "script and style contents remain raw" $ raw `isInfixOf` outputRaw
  outputText <- addImgDimensions $ "<p title=\"A &amp; B\">&lt;col&gt; &amp; text</p>" ++ image
  assert "text and attribute entities remain escaped" $ "<p title=\"A &amp; B\">&lt;col&gt; &amp; text</p>" `isInfixOf` outputText
  putStrLn "HTML image serialization regression tests passed."
