#!/usr/bin/env python3


from panflute import *
import re
import sys
from typing import List

# Import local files
from whitespace import *
from command import *
from util import *

from mj_show import show

flags = ["dog"]
commands = {}

def executeCommand(source: Code, element: Element) -> List[Element]:
	mode = 'empty'
	text = ""
	content = []
	def print(s: str=""):
		nonlocal mode, text
		if mode == 'elements':
			raise SyntaxError("Cannot use `print` and `appendChild` in one command at the same time.")
		mode = 'text'
		text += s
	
	def println(s: str=""):
		print(s+"\n")

	def appendChild(e: Element):
		nonlocal mode, content
		if mode == 'text':
			raise SyntaxError("Cannot use `print` and `appendChild` in one command at the same time.")
		mode = 'elements'
		content.append(e)
	
	def appendChildren(l: List[Element]):
		for e in l:
			appendChild(e)

	exec(source)

	if mode == 'text':
		return convert_text(text)
	if mode == 'elements':
		return content

	return []

def transform(e: Element, doc: Doc) -> Element: # Returns next sibling element to transform
	"""Transform the AST, making format-agnostic changes."""

	global commands
	global flags
	
	if isinstance(e, Whitespace) and bavlna(e):
		e = NBSP()

	if hasattr(e, "attributes"):
		# `if` attribute. Only show this element if flag is set.
		if "if" in e.attributes:
			if not e.attributes["if"] in flags:
				return nullify(e)
		# `ifn` attribute. Only show this element if flag is NOT set
		if "ifn" in e.attributes:
			if e.attributes["ifn"] in flags:
				return nullify(e)
		
		# `c` attribute. Execute a command with the name saved in this attribute.
		if (isinstance(e, Div) or isinstance(e, Span)) and "c" in e.attributes:
			if isinstance(e, Div):
				e = MultilineCommand(*e.content, identifier=e.identifier, classes=e.classes, attributes=e.attributes)
			else:
				e = InlineCommand(*e.content, identifier=e.identifier, classes=e.classes, attributes=e.attributes)
	
	
	# Execute python code inside source code block
	if isinstance(e, CodeBlock) and hasattr(e, "classes") and "python" in e.classes and "run" in e.classes:
		exec(e.text)
		return nullify(e)
	
	## Define commands
	# TODO: def/longdef?
	if isinstance(e, CodeBlock) and hasattr(e, "classes") and "python" in e.classes and hasattr(e, "attributes"):
		if "define" in e.attributes:
			if not e.attributes["define"] in commands:
				commands[e.attributes["define"]] = compile(e.text, '<string>', 'exec')
				return nullify(e)
			else:
				raise NameError(f"Command already defined: '{e.attributes['define']}'")
		if "redefine" in e.attributes:
			commands[e.attributes["redefine"]] = compile(e.text, '<string>', 'exec')
			return nullify(e)
	
	if isinstance(e, Span) and len(e.content) == 1 and isinstance(e.content[0], Str):
		print(isinstance(e, Span))
		## Handle special command shorthand [!commandname]{}
		if re.match(r"^![\w.]+$", e.content[0].text):
			e = InlineCommand(identifier=e.identifier, classes=e.classes, attributes={**e.attributes, "c": e.content[0].text[1:]})

		## Handle include [>path/file.md]{} TODO: implement properly as commands
		# This is for including content from files with their own flags
		# and commands without affecting the state of the current
		# document.
		elif re.match(r"^>.+$", e.content[0].text):
			includedDoc = convert_text(open(e.content[0].text[1:], "r").read(), standalone=True) # TODO: Put into function
			oCommands = commands.copy()
			oFlags = flags[:]
			includedDoc = includedDoc.walk(transform)
			commands = oCommands
			flags = oFlags
			#e = Div(*includedDoc.content)
		
		## Handle import [#path/file.md]{} TODO: implement properly as commands
		# This is the exact opposite of include. We take the commands
		# and flags but drop the content.
		elif re.match(r"^#.+$", e.content[0].text):
			importedDoc = convert_text(open(e.content[0].text[1:], "r").read(), standalone=True) # TODO: Put into function
			importedDoc.walk(transform)
			return nullify(e)

	## Execute commands
	# Walk transforms the children first, then the root element,
	# so the content of the element the command receives is
	# already transformed.
	# TODO: Transform content that comes out of commands.
	if isinstance(e, Command):
		if not e.attributes["c"] in commands:
			raise NameError(f"Command not defined '{e.attributes['c']}'.")
		e = e.replaceSelf(executeCommand(commands[e.attributes["c"]], e))
	
	return e


doc = convert_text(open(sys.argv[1], "r").read(), standalone=True) # TODO: Put into function so we can specify extensions and parameters globally.


print(show(doc))
doc = doc.walk(transform)
print("---------------------")
#print(show(doc))
print(convert_text(doc, input_format="panflute", output_format="markdown"))