from __future__ import annotations

import base64

from pygitweb.static_tests.js_runtime import JsPage

_DIFF = base64.b64encode(b"diff --git a/a b/a\n").decode("ascii")
_SHELL = (
	'<div id="d2h-container" data-diff-b64="{b64}" data-has-diff="{has}" data-empty-text="{empty}"></div>'
	'<div id="d2h-output"></div><div id="d2h-empty"></div>'
)


def _stub_diff2html(js: JsPage) -> None:
	js.run(
		"globalThis.Diff2HtmlUI = function(el, diff, config) {"
		" this.el = el; this.diff = diff; this.config = config;"
		" el.setAttribute('data-diff', diff);"
		" el.setAttribute('data-format', config.outputFormat);"
		" this.draw = function() { el.setAttribute('data-drawn', '1'); };"
		" this.highlightCode = function() { el.setAttribute('data-hl', '1'); };"
		"};"
	)


def test_render_does_nothing_when_nodes_are_missing(js: JsPage) -> None:
	js.set_html("<div></div>")
	js.load("diff-view.js")
	assert js.count("#d2h-empty") == 0


def test_render_shows_empty_text_when_there_is_no_diff(js: JsPage) -> None:
	js.set_html(_SHELL.format(b64="", has="false", empty="No changes"))
	js.load("diff-view.js")
	assert js.text("#d2h-empty") == "No changes"
	assert js.value("document.querySelector('#d2h-empty').style.display") == "block"


def test_render_shows_empty_text_when_base64_is_missing(js: JsPage) -> None:
	js.set_html(_SHELL.format(b64="", has="true", empty="Empty"))
	js.load("diff-view.js")
	assert js.text("#d2h-empty") == "Empty"


def test_render_draws_a_decoded_diff(js: JsPage) -> None:
	_stub_diff2html(js)
	js.set_html(_SHELL.format(b64=_DIFF, has="true", empty=""))
	js.load("diff-view.js")
	assert js.attr("#d2h-output", "data-drawn") == "1"
	assert js.attr("#d2h-output", "data-hl") == "1"
	assert "diff --git" in (js.attr("#d2h-output", "data-diff") or "")
	assert js.attr("#d2h-output", "data-format") == "side-by-side"


def test_render_treats_an_empty_decode_as_no_diff(js: JsPage) -> None:
	js.run("globalThis.atob = function() { return ''; };")
	js.set_html(_SHELL.format(b64=_DIFF, has="true", empty="Blank"))
	js.load("diff-view.js")
	assert js.text("#d2h-empty") == "Blank"


def test_render_uses_the_raw_string_without_textdecoder(js: JsPage) -> None:
	_stub_diff2html(js)
	js.run("globalThis.__td = globalThis.TextDecoder; delete globalThis.TextDecoder;")
	js.set_html(_SHELL.format(b64=_DIFF, has="true", empty=""))
	js.load("diff-view.js")
	js.run("globalThis.TextDecoder = globalThis.__td;")
	assert js.attr("#d2h-output", "data-drawn") == "1"


def test_render_escapes_a_decoder_error(js: JsPage) -> None:
	js.set_html(_SHELL.format(b64="!!!", has="true", empty=""))
	js.load("diff-view.js")
	html = js.prop("#d2h-output", "innerHTML")
	assert "Failed to render diff" in html
	assert "<script" not in html
	assert "&lt;" in html or "Invalid" in html