#!/usr/bin/env python3

import os
import sys
import argparse
import re
import shutil
import subprocess
import shlex
import copy

import jsExtractFunctions as jsef;
import ClassJsRef as ClassJsRef;


# The main directory will be the top source directory: development
mainDir = os.path.normpath(os.getcwd());
# print("mainDir:" + mainDir + "\n");

parser = argparse.ArgumentParser(description='''Script to extract
JavaScript-related reference text from source code files.''')

# parser.add_argument('-i', '--infiles', metavar='input_file', nargs='+',
# 										required = False, help='Source files to process.')

parser.add_argument('-t', '--tab', metavar='tabulator', required = False, help='String representing a tabulation key hit')

parser.add_argument('-o', '--outfile', metavar='output file', nargs='?', required = False, help='File name to output the results to (or the console if not specified.')

parser.add_argument('-l', '--listfile', metavar='file-list file', nargs='?', required = False, help='Name of the file that contains the list of files to process.')

parser.add_argument('-d', '--dir', metavar='dir', nargs='?', required = False, help='Directory where the listing of the JS reference-containing files should occur.')

group = parser.add_mutually_exclusive_group(required=True)

group.add_argument('--extract',
                    choices=['class', 'enum'],
                    help='Extract reference for specific type. Provide a list of files to be processed with the --infiles argument.')

group.add_argument('--list-files',
                    choices=['class', 'enum'],
                    help='List files having reference for specific type.')

args = parser.parse_args()

if args.tab:
	if args.tab == "\\t":
		tab = "\t"
	else:
		tab = args.tab
else:
	#tab = "\n"
	tab = "  "

# if args.infiles:
# 	print(f"Input files: {args.infiles}")
#
# if args.outfile:
# 	print(f"Output file: {args.outfile}")
#
# if args.extract:
# 	print(f"Extracting {args.extract}")
#
# if args.list:
# 	print(f"Listing {args.list}")


if args.listfile:
	with open(args.listfile, 'r') as f:
		content = f.read()
		# print(f"The contents of the file: {content}")
		args.infiles = content


if args.list_files:

	if args.dir:
		root_dir = args.dir
	else:
		root_dir = os.getcwd()

	if args.list_files == "class":
		file_list = jsef.listAllJsRefFiles(root_dir,
			"BEGIN CLASS JS REFERENCE")

	elif args.list_files == "enum":

		file_list = jsef.listAllJsRefFiles(root_dir,
			"BEGIN ENUM JS REFERENCE")

	# print(f"The listed files found in {root_dir}:\n {file_list}")

	# Now generate a list of files that is injectable to this same program
	# as the --infiles parameter.

	all_files_in_a_string =""

	for file in file_list:
		if file is not None:
			# print(f"{file} ")
			sys.stdout.write(file + ' ')

			#all_files_in_a_string = all_files_in_a_string + f" {file}"

	#print(all_files_in_a_string)


if args.extract:

	if not args.infiles:
		print("Provide a list of header file paths to process or the name of a file that contains that list.", file = sys.stderr)
		exit(1)

	# This is a list of ClassJsRef instances.
	all_class_js_ref_results = [ ]

	if args.extract == "class":

		# args.infiles is a list
		#print(type(args.infiles))

		file_list = args.infiles.split(' ')

		for file in file_list:

			# Now file is a string corresponding to a single file name.
			#print(type(file))
			# print(f"Current file: {file}")

			if file is not None and len(file) > 0:
				# simplified_file = re.sub(r'\s$', '', file)
				# print(f"\nNow processing file '{file}'\n\n")

				# The returned object is a list of ClassJsRef instances
				# in case more than one class is JS reference documented.
				class_js_ref_results = jsef.extract_class_js_reference(file)

				# print(f"Classes parsed in {file}:\n")

				for class_js_ref in class_js_ref_results:
					print(f"{str(class_js_ref)}\n")

					# There might be nothing in there as Q_PROPERTY or Q_INVOKABLE stuff
					if not len(class_js_ref.properties) and not len(class_js_ref.invokables):
						# print("For id {results[0]}n there were no Q_PROPERTY or Q_INVOKABLE")
						pass
					else:
						all_class_js_ref_results.append(class_js_ref)


		# print("All the results:\n")
		# all_class_js_ref_results is a list of  [ id, properties, invokables]
		# with id a tuple(name_space, class_name)
		# with properties a [ property_string ]
		# with invokables a [ invokable_string ]

		offset = 0

		#print(f"Text{lead}four tabs")
		#print(f"Text{tab}one tabs")

		if args.outfile:

			# print(f"Now outputting the extracted JS reference text to:\n{args.outfile}\n")

			from pathlib import Path
			file_path = Path(args.outfile)

			file_handle = file_path.open('w', encoding='utf-8')

			for class_js_ref_result in all_class_js_ref_results:

				file_handle.write(class_js_ref_result.get_as_text(tab, offset))

		else:

			# print(f"Now outputting the extracted JS reference text to terminal\n")

			for class_js_ref_result in all_class_js_ref_results:

				class_js_ref_result.print(tab, offset)
