#!/usr/bin/env python3

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

import jsExtractFunctions as jsef;

# First of all check that we are in the development main source directory, that
# is, that the current directory contains the "debian" directory.
if not os.path.exists("debian"):
    print('''No debian directory found. Please change directory to the
      top source directory''')
    exit(1);

# 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 documentation from source code files.''')

parser.add_argument('-i', '--inFiles', metavar='input file', nargs='+', required = False,
    help='source files to process')

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

parser.add_argument('-l', '--listJsFiles', action='store_true',
    help = "List all files that contain JavaScript doc stanzae.")

args = parser.parse_args()

# inFiles is a list
inFiles = args.inFiles;

# if inFiles:
    # print("inFiles: " + ", ".join(inFiles));

outFileName = "";
if args.outFile:
    # print("args.outFile: " + args.outFile);
    outFileName = args.outFile;

# The user might only want to list all the files that contain JS-related
# documentation.
listJsFiles = args.listJsFiles;

if listJsFiles:
    jsef.listAllJsDocFiles();
    exit(0);

# We want to iterate in the various directories (these are related to the
# namespaces) of the project and for each file in it, get its file name, that is
# the class name. Then look in sequence in the hpp and cpp files and extract all
# the documentation that is enclosed in the /*/js* ... */ comment delimiters.

# Because there are multiple files related to JavaScript'ing, the files that
# contain useful JS stuff need to declare themselves and the class they contain
# using a JS comment like this one:

# /*/js/ Class: MassSpectrum
#  */

# The general form of documentation for the JS stuff is like the following:

# /*/js/
#  * MassSpectrum()
#  *
#  * constructor of a MassSpectrum object
#  */

# or like this:

# /*/js/
#  * MassSpectrum.initialize(mzArray, iArray, mzStart, mzEnd)
#  *
#  * initialize this MassSpectrum object with two <Array> of numerical
#  * values and two <Number> entities delimiting a range of acceptable m/z
#  * values.
#  *
#  * mzArray: <Array> object containing the m/z values of the spectrum
#  * iArray: <Array> object containing the intensity values of the spectrum
#  * mzStart: m/z value used to filter the data points to be used for the
#  * initialization (the start of the acceptable m/z range)
#  * mzEnd: m/z value used to filter the data points to be crafted for the
#  * initialization (the end of the acceptable m/z range)
#  */

# So one can see that the documentation marker is /*/js/ [...] */

# We want to cycle in all the [ch]pp files in all the directories in search for JS markup

stanzaListList = [ ];
classList = [ ];
tagList = [ ];
commentList = [ ];

for fileName in inFiles:
    print("Processing " + fileName);
    jsef.processFile(fileName, stanzaListList, classList, tagList, commentList);

print("classList size: " + str(len(classList)));
print("tagList size: " + str(len(tagList)));
print("commentList size: " + str(len(commentList)));
print("stanzaListList size: " + str(len(stanzaListList)));
print("\n\n");

# If an output filename was provided, then redirect all the print() statements
# to the file handle. Otherwise, let the print() statements print to sys.stdout.
if outFileName:
    fileHandle = open(outFileName, 'w');
    sys.stdout = fileHandle;

for iter in range(0, len(classList)):

    # print("Now iterating in all the lists\n");

    className = classList[iter];
    comment = commentList[iter];

    # print('''tagName: {tagName}\nclassName: {className}\n'''.format(tagName = tagList[iter],
        # className = className));

    stanzaList = stanzaListList[iter];

    # print("For class name " + className + ", the number of stanzae: " +
        # str(len(stanzaList)));

    print(className + "\n");

    if comment:
        print(comment + "\n");

    for stanza in stanzaList:
        # print("New stanza for documentation of {} {}\n".format(tagList[iter], classList[iter]));

        count = 0;
        for line in stanza:

            # print(">>>>>>>>>>>line: " + str(line));
            regexp = re.compile("^\s*\**\s*(.*)$");
            match = regexp.match(line);

            lineText = match.group(1);

            # Check if the line only contains whitespaces
            lineText.strip();

            if count == 0:
                # This is the first line of the stanza, so we do only one
                # indentation of two spaces. But we do this only if the line is
                # *not* empty.
                if not lineText:
                    print("");
                else:
                    print("  " + lineText);
            else:
                  # If not first line of the stanza, then indent the line twice.
                  # But only if the line is *not* empty.
                  if not lineText:
                      print("");
                  else:
                      print("    " + lineText);

            # Let know that the first line was encountered already
            count +=1;

        print("\n");

