import os
import sys
import argparse
import re
import shutil
import subprocess
import shlex
import copy
import itertools
from pathlib import Path

import ClassJsRef as ClassJsRef
import QinvokableJsRef as QinvokableJsRef
import QpropertyJsRef as QpropertyJsRef

# Matches ... namespace: ... line
name_space_regex_string = r"^\s*\*?\s*namespace\s*:\s*([^\s.]+)\s*$"
name_space_regex = re.compile(name_space_regex_string)

# Matches ... class name: ... line
class_name_regex_string = r"^\s*\*?\s*class name\s*:\s*([^\s.]+)\s*$"
class_name_regex = re.compile(class_name_regex_string)

# Matches property type and property name
property_regex_string = r"^\s*Q_PROPERTY\(\s*([^\s.]+)\s+(\*?\s*[^\s?]+).*$"
property_regex = re.compile(property_regex_string)

# Matches everything after Q_INVOKABLE
invokable_regex_string = r"^\s*Q_INVOKABLE\s*(.*)$"
invokable_regex = re.compile(invokable_regex_string)


def parse_q_property_block(opening_line, file_handle):

	# opening_line can start these two ways:

	# 1. /*$ JS PROP REF The .... .... */
	# 2. Q_PROPERTY(Type variable WRITE write READ read)

	q_property_js_ref = QpropertyJsRef.QpropertyJsRef()

	ref_line_found = False

	js_ref_lines = [ ]
	statement_lines = [ ]

	opening_line = re.sub(r'^\s*', '', opening_line)
	opening_line = re.sub(r'\s*\n$', '', opening_line)


	if "$ JS PROP REF" in opening_line:

		# print(f"JS PROP REF: {opening_line}")

		ref_line_found = True

		js_ref_lines.append(opening_line)

		if "*/" not in opening_line:

			# print("*/ not in opening_line, multiline text")

			while(True):

				line = file_handle.readline()
				line = line.replace('\n', '')
				# In multiline, there will be chars at the beginning
				# and maybe at the end. Remove them because we need
				# to join the lines laters with ' ' and we do not want
				# multiple spaces in the finished text line.
				line = re.sub(r'^\s*', '', line)
				line = re.sub(r'\s*$', '', line)

				# print(f"Read follow-up JS PROP REF line '{line}'")
				js_ref_lines.append(line)

				if "*/" in line:

					# We have finished the JS REF block for the property to come.
					break;


		# Join the lines into a single string
		js_ref_as_single_line = " ".join(js_ref_lines)

		# Now purify:

		js_ref_as_single_line = re.sub(r'^\s*/\*\s*\$\s*JS PROP REF\s*', '', js_ref_as_single_line)
		js_ref_as_single_line = re.sub(r'\s*\*/', '', js_ref_as_single_line)

		# print(f"as a single line: {js_ref_as_single_line}")

		q_property_js_ref.description.append(js_ref_as_single_line)

		# print(f"After purification of property js ref: {q_property_js_ref.get_description_as_text("  ", 0)}")

	# At this point we need to know if we had a JS REF line or not

	if ref_line_found:
		# We need to read a line
		opening_line = file_handle.readline()

	if "Q_PROPERTY" not in opening_line:
		print("Failed to parse JS REF / Q_PROPERTY line", file=sys.stderr)
		sys.exit(1)

	statement_lines = [ opening_line.replace('\n', '')  ];

	#  If the first line of the Q_PROPERTY statement
	# does not end by ')', then we are dealing with a
	# multiline block.

	if ')' not in opening_line:

		# print("Character ')' is not in the opening_line, this is a multi-line Q_PROPERTY statement")

		while(True):

			line = file_handle.readline()
			line = line.replace('\n', '')
			# print(f"Read follow-up Q_PROPERTY line {line}")
			statement_lines.append(line)

			if ')' in line:
				# print("Character ')' is in the follow-up line")
				# We are done. Exit the loop.
				break;

	else:
		pass
		#print("')' was found in the opening line");

	# At this point we finally encountered the ')', either
	# because it was on the first block opening line or
	# because we iterated in next lines in the file.

	# So now make a single text string out of the string list
	statement_as_single_line = " ".join(statement_lines)

	#print(f"Joined: {statement_as_single_line}")
	simplified_statement_single_line = re.sub(r'\s+', ' ', statement_as_single_line)
	#print(f"Simplified {simplified_statement_single_line}")

	match = property_regex.match(simplified_statement_single_line);

	if(match):

		# print(f"Matched Q_PROPERTY: {match.group(1)} {match.group(2)}")
		q_property_js_ref.statement = f"{match.group(1)} {match.group(2)}"
		# print(f"Returning QpropertyJsRef {str(q_property_js_ref)}")

		return q_property_js_ref

	else:

		print("Failed to extract Q_PROPERTY statement.", file=sys.stderr)
		sys.exit(1)


def parse_q_invokable_block(opening_line, file_handle):

	# opening_line can start these two ways:

	# 1. /*$ JS INVOK REF The .... .... */
	# 2. Q_INVOKABLE explicit Utils(QObject *parent = nullptr);

	q_invokable_js_ref = QinvokableJsRef.QinvokableJsRef()

	ref_line_found = False

	js_ref_lines = [ ]
	invokable_lines = [ ]

	opening_line = re.sub(r'^\s*', '', opening_line)
	opening_line = re.sub(r'\s*\n$', '', opening_line)


	if "$ JS INVOK REF" in opening_line:

		# print(f"JS INVOK REF: {opening_line}")

		ref_line_found = True

		js_ref_lines.append(opening_line)

		if "*/" not in opening_line:

			# print("*/ not in opening_line, multiline text")

			while(True):

				line = file_handle.readline()
				line = line.replace('\n', '')
				# In multiline, there will be chars at the beginning
				# and maybe at the end. Remove them because we need
				# to join the lines laters with ' ' and we do not want
				# multiple spaces in the finished text line.
				line = re.sub(r'^\s*', '', line)
				line = re.sub(r'\s*$', '', line)

				# print(f"Read follow-up JS INVOK REF line {line}")
				js_ref_lines.append(line)

				if "*/" in line:

					# We have finished the JS REF block for the invokable to come.
					break;


		# Join the lines into a single string
		js_ref_as_single_line = " ".join(js_ref_lines)

		# Now purify:

		js_ref_as_single_line = re.sub(r'^\s*/\*\s*\$\s*JS INVOK REF\s*', '', js_ref_as_single_line)
		js_ref_as_single_line = re.sub(r'\s*\*/', '', js_ref_as_single_line)

		# print(f"After purification of invokable js ref: {js_ref_as_single_line}")

		q_invokable_js_ref.description.append(js_ref_as_single_line)

	# At this point we need to know if we had a JS REF line or not

	if ref_line_found:
		# We need to read a line
		opening_line = file_handle.readline()

	if "Q_INVOKABLE" not in opening_line:
		print("Failed to parse JS REF / Q_INVOKABLE line", file=sys.stderr)
		sys.exit(1)

	statement_lines = [ opening_line.replace('\n', '')  ];

	#  If the first line of the Q_INVOKABLE statement
	# does not end by ';', then we are dealing with a
	# multiline block.

	if ';' not in opening_line:

		# print("Character ';' is not in the opening_line, this is a multi-line Q_INVOKABLE statement")

		while(True):

			line = file_handle.readline()
			line = line.replace('\n', '')
			statement_lines.append(line)

			if ';' in line:
				# print("Character ';' is in the follow-up line")
				# We are done. Exit the loop.
				break;

	else:
		# print("';' was found in the opening line");
		pass

	# At this point we finally encountered the ';', either
	# because it was on the first block opening line or
	# because we iterated in next lines in the file.

	# So now make a single text string out of the string list
	statement_as_single_line = " ".join(statement_lines)

	# print(f"Joined: {statement_as_single_line}")
	simplified_statement_single_line = re.sub(r'\s+', ' ', statement_as_single_line)
	# print(f"Simplified {simplified_statement_single_line}")

	match = invokable_regex.match(simplified_statement_single_line);

	if(match):

		# print(f"Matched Q_INVOKABLE: '{match.group(1)}'")
		q_invokable_js_ref.statement = match.group(1)
		# print(f"Returning QinvokableJsRef with {q_invokable_js_ref.statement}")

		return q_invokable_js_ref

	else:
		print("Failed to extract Q_INVOKABLE statement.", file=sys.stderr)
		sys.exit(1)


def parse_description_block(opening_line, file_handle):

	# print(f"Opening line for BEGIN DESCRIPTION")

	description_block_list = [ ];

	# Store all the lines between this opening line and
	# the line that reads "END DESCRIPTION"

	# Pattern matches lines that start with optional whitespace followed by *
	# and some more optional spaces. We want to keep all the spaces to
	# maintain proper formatting.
	remove_star_and_spaces_in_start_pattern = r'^(\s*\*\s*)'

	while(True):

		line = file_handle.readline()

		if not "END DESCRIPTION" in line:

			new_line = re.sub(remove_star_and_spaces_in_start_pattern,
										 r'', line, flags=re.MULTILINE)

			# print(f"Adding new description block line: '{new_line}'")
			description_block_list.append(new_line)
		else:
			break

	# return ("").join(description_block_list)
	return description_block_list


def extract_class_js_reference(header_path):
	"""Returns [ id, properties, invokables]
		 with id = (name_space, class_name)"""

	# print(f"header_path: {header_path}");

	if not os.path.exists(header_path):
		print("File " + header_path + " was not found\n", file = sys.stderr);
		return;

	# We want to iterate in the file  in search for the JS markup of classes
	# that is in the form right before the class declaration:
	#
	# /*  BEGIN JS REFERENCE
	#			namespace: MsXpS::libXpertMassCore
	# 		class name: Polymer
	# */
	#
	# and
	# /*  END JS REFERENCE
	#     namespace: MsXpS::libXpertMassCore
	#     class name: Polymer
	# */
	# right after the class declaration

	# Note that we may have more than one class
	# with JS reference text, so we will return
	# the results as a list.

	parsed_class_js_ref_texts = [ ]

	js_ref_block_opened = False;

	# Closed when first ';' is encountered.
	invokable_block_opened = False;


	# full_js_ref = [ id , properties, invokables ];
	full_js_ref = [ ];

	with open(header_path) as fileHandle:
		line = fileHandle.readline()

		while line:

			if re.match(r'^\s*//', line):
				line = fileHandle.readline()

			# print(f"New line is: {line}");

			if "BEGIN CLASS JS REFERENCE" in line:

				# We are starting a JS reference block

				# Instantiate a class to be used as the
				# container for all the data.
				class_js_ref = ClassJsRef.ClassJsRef()

				js_ref_block_opened = True;

				line = fileHandle.readline()
				# print(f"Parsed line inside BEGIN CLASS JS REFERENCE: {line}")

				# Check if namespace: ... line
				match = name_space_regex.match(line);
				if match:

					if not js_ref_block_opened:
						print("Cannot have name space if JS ref block not opened", file=sys.stderr)
						sys.exit(1)

					name_space = match.group(1);
				else:
					print("Failed to parse the namespace", file=sys.stderr)
					sys.exit(1)

				line = fileHandle.readline()
				# print(f"Parsed line inside BEGIN CLASS JS REFERENCE: {line}")

				# Check if class name: ... line
				match = class_name_regex.match(line);
				if match:

					if not name_space:
						print("Cannot have class name if no name space.", file=sys.stderr)
						sys.exit(1)

					class_name = match.group(1);

					class_js_ref.name_space = name_space
					class_js_ref.class_name = class_name

					# print(f"Could set the name space and class name: {class_js_ref.name_space} - {class_js_ref.class_name}")

				else:
					print("Failed to parse the class name", file=sys.stderr)
					sys.exit(1)


			if "BEGIN DESCRIPTION" in line:
				class_js_ref.description = parse_description_block(line, fileHandle)
				if(len(class_js_ref.description)):
					# print(f"Set description for class {class_js_ref.class_name} is:\n {class_js_ref.description}")
					pass


			if "JS PROP REF" in line or "Q_PROPERTY" in line:

				# print("Detected line with JS PROP REF")

				if not len(class_js_ref.name_space) or not len(class_js_ref.class_name):
					print("Cannot be that a Q_PROPERTY block is opened while there is no name space nor class name.", file=sys.stderr);
					sys.exit(1)

				q_property_js_ref = parse_q_property_block(line, fileHandle)
				q_property_js_ref.name_space = class_js_ref.name_space
				q_property_js_ref.class_name = class_js_ref.class_name

				class_js_ref.properties.append(q_property_js_ref)

				# print(f"Appended new Q_PROPERTY: {q_property_js_ref.statement}")


			if "JS INVOK REF" in line or "Q_INVOKABLE" in line:

				# print("Detected line with JS INVOK REF")

				if not len(class_js_ref.name_space) or not len(class_js_ref.class_name):
					print("Cannot be that a Q_INVOKABLE block is opened while there is no name space nor class name.", file=sys.stderr);
					sys.exit(1)

				q_invokable_js_ref = parse_q_invokable_block(line, fileHandle)
				q_invokable_js_ref.name_space = class_js_ref.name_space
				q_invokable_js_ref.class_name = class_js_ref.class_name

				class_js_ref.invokables.append(q_invokable_js_ref)

				# print(f"Appended new Q_INVOKABLE: {q_invokable_js_ref.statement}")


			if "END CLASS JS REFERENCE" in line:

				if not js_ref_block_opened:
					print("Cannot be that JS ref. block is being closed while it was never opened.", file=sys.stderr)
					sys.exit(1)

				if not len(class_js_ref.name_space) or not len(class_js_ref.class_name):
					print("Cannot be that a Q_PROPERTY block is opened while there is no name space nor class name.", file=sys.stderr);
					sys.exit(1)

				line = fileHandle.readline()
				# print(f"line: {line}")

				# Make sure we are closing the right class JS reference block
				match = name_space_regex.match(line);
				if match:

					end_name_space = match.group(1);
					if end_name_space != name_space:
						print("Cannot be that a JS ref. block is closed with another name space.", file=sys.stderr)
						sys.exit(1)
				else:
					print("The class JS reference block fails to close correctly.", file=sys.stderr)
					sys.exit(1)

				line = fileHandle.readline()
				# print(f"line: {line}")

				match = class_name_regex.match(line);
				if match:

					end_class_name = match.group(1);
					if end_class_name != class_name:
						print("Cannot be that a JS ref. block is closed with another class name.", file=sys.stderr)
						sys.exit(1)

				js_ref_block_opened = False

				# So we've done parsing one class JS reference text, add the instantiated
				# class to the returned list.

				parsed_class_js_ref_texts.append(class_js_ref)

			# Go on with potential new class with JS reference text.
			line = fileHandle.readline()

		# print(f"Finished parsing {header_path}\n")

	return parsed_class_js_ref_texts


def listAllJsRefFiles(root_dir, js_ref_bock_tag):

		root_path = Path(root_dir)
		matching_files = []


		# Recursively search for both .hpp and .h files
		hpp_files = root_path.rglob("*.hpp")
		h_files = root_path.rglob("*.h")

		# Combine both iterators
		all_header_files = itertools.chain(hpp_files, h_files)

		for header_file in all_header_files:

				try:
						with open(header_file, 'r', encoding='utf-8') as f:
								content = f.read()
								if js_ref_bock_tag in content:
										matching_files.append(str(header_file))

				except (UnicodeDecodeError, PermissionError, OSError) as e:
						print(f"Could not read {header_file}: {e}", file=sys.stderr)

		return matching_files
