import io
import glob
import json
import os
from pathlib import Path
import re
import subprocess

def jsToHtml(jsPath, htmlDir, templatePath):
    htmlPath = Path(os.path.join(htmlDir, os.path.basename(jsPath.with_suffix('.html'))))

    with io.open(jsPath, 'r') as jsFile:
        # Strip out the js specific stuff to turn it into json
        inText = re.sub(r"(files(.*?)= )|(^[\/\/].*)", "", jsFile.read(), flags=re.MULTILINE)
        data = json.loads(inText)
        name = data["title"]
        referenceFiles = data["referenceFiles"] if "referenceFiles" in data else []

    # Fill out the html template with the filename
    with io.open(templatePath, 'r') as templateFile:
        formattedTemplate = re.sub(r"<##>", name, templateFile.read(), flags=re.MULTILINE)
        formattedTemplate = re.sub(r"<@@>", jsPath.stem, formattedTemplate, flags=re.MULTILINE)

        # Populate reference files
        if referenceFiles and len(referenceFiles) > 0:
            formattedReferenceFiles = ""
            for referenceFile in referenceFiles:
                formattedReferenceFiles += "    <script src=\"../data/files/" + referenceFile + ".js\"></script>\n"
            formattedTemplate = re.sub(r".*<\$\$>(.*\r?\n)", formattedReferenceFiles, formattedTemplate, flags=re.MULTILINE)
        else:
            formattedTemplate = re.sub(r".*<\$\$>(.*\r?\n)", "", formattedTemplate, flags=re.MULTILINE)
            
    with io.open(htmlPath, 'w') as htmlFile:
        output = "<!-- Generated by generate-html-files.py -->\n" + formattedTemplate
        htmlFile.write(output)

def generateHtmlFiles(dataPath, filesPath, usePerforce):
    templatePath = Path(os.path.join(dataPath, "template.html"))
    if not os.path.exists(templatePath):
        print ("ERROR: template.html does not exist at {}".format(templatePath))
        return False

    dataFilesPath = os.path.join(dataPath, "files")
    if (usePerforce):
        # Gather perforce files to checkout or add
        p4EditString = ""
        p4AddString = ""
        for jsFilepath in glob.glob(os.path.join(dataFilesPath, '*.js')):
            htmlPath = Path(os.path.join(filesPath, os.path.basename(Path(jsFilepath).with_suffix('.html'))))
            if os.path.exists(htmlPath):
                p4EditString += htmlPath.name + " "
            else:
                p4AddString += htmlPath.name + " "

        # Check out or add files
        htmlDirPath = Path(filesPath)
        if p4EditString:
            subprocess.run("p4 edit " + p4EditString, check=True, shell=True, cwd=htmlDirPath)
        if p4AddString:
            subprocess.run("p4 add " + p4AddString, check=True, shell=True, cwd=htmlDirPath)

    # Generate a .html for every .js file
    for jsFilepath in glob.glob(os.path.join(dataFilesPath, '*.js')):
        jsToHtml(Path(jsFilepath), filesPath, templatePath)

    if (usePerforce):
        # Revert unchanged files from perforce
        subprocess.run("p4 revert -a -c default", check=True, shell=True, cwd=htmlDirPath)
        
    return True
