# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3.9.7 64-bit
#     name: python3
# ---

# +
from glob import glob
import re
import json
def loadFile(file_name) :
    with open(file_name, "r") as f :
        return "".join(f.readlines())
    return ""

def saveFile(file_name, contents) :
    with open(file_name, "w") as f :
        f.write(contents)

def loadJson(json_file_path) :
    with open(json_file_path, encoding='utf-8') as json_file :
        return json.load(json_file)

def camel2Sname(name) :
    return re.sub(r'(?<!^)(?=[A-Z])', '_', name).lower()

def camel2SnameSpace(name) :
    return re.sub(r'(?<!^)(?=[A-Z])', ' ', name).lower()


simpleApi = loadJson("../ngx3js-module/docs_api.json")["children"]

i3JSApi = None
for info in simpleApi :
    if (info["name"] == "I3JS") :
        i3JSApi = info["children"]


# +
def getClassInfo(className : str) :
    for info in i3JSApi :
        if (info["name"] == className) :
            return info
    for info in simpleApi :
        if (info["name"] == className) :
            return info
    return None

def getSourceFile(info) :
    if "sources" in info :
        fileName : str = info["sources"][0]["fileName"]
        if fileName.startswith("lib/") :
            return fileName[0:-3]
    return "error"

def isDecorators(info, decoType) :
    isInput = False
    if 'decorators' in info :
        decorators = info['decorators']
        for deco in decorators :
            if deco['name'] == decoType :
                isInput = True
    return isInput

def getExtends(info) :
    extendeds = []
    if "extendedTypes" in info : 
        extendedTypeName = info["extendedTypes"][0]["name"]
        childInfo = getClassInfo(extendedTypeName)
        if childInfo is not None :
            parentExtends = getExtends(childInfo)
            if len(parentExtends) > 0 :
                for name in parentExtends :
                    extendeds.append(name)
        extendeds.append(extendedTypeName)
    return extendeds



def getGenApiDocs(className : str) :
    info = getClassInfo(className)
    if info is None :
        return False
    kindString = info["kindString"]
    parentkindString = kindString
    html = []
    html.append('<!DOCTYPE html>')
    html.append('<html lang="en">')
    html.append('	<head>')
    html.append('		<meta charset="utf-8" />')
    html.append('		<base href="../../" />')
    html.append('		<script src="page.js"></script>')
    html.append('		<link type="text/css" rel="stylesheet" href="page.css" />')
    html.append('	</head>')
    html.append('	<body>')
    refTypes = []
    fileName = getSourceFile(info)
    nameSpace = None
    if kindString == "Namespace" :
        html.append('		<h1>{0}</h1>'.format(className))
        html.append('')
        html.append('		<h2>Namespace</h2>')
        if 'children' in info :
            for child in info['children'] :
                typeName = child['name']
                childkindString = child['kindString']
                if childkindString == 'Variable':
                    defaultValue = ''
                    typeName = getParamTypes(child)
                    if 'defaultValue' in child and child['defaultValue'] != 'null':
                        defaultValue = ' &nbsp; = {0} '.format(child['defaultValue'])
                    html.append('		<h3>[property:{1} {0}]{2}{4}{3}</h3>'.format(
                        child['name'], 
                        typeName,
                        '',
                        '',
                        defaultValue
                    ))
                    refTypes.append(typeName)
                    html.append('		<p>\n\t\t\t{0}\n\t\t</p>'.format(getComment(child)))
                    html.append('')
                else :
                    extends = getExtends(child)
                    interfaceHtml = getExtraInterFace(child, extends)
                    if interfaceHtml is not None and len(interfaceHtml) > 0 :
                        mChildName = child['name']
                        extendHtml = []
                        if len(extends) > 0 :
                            for ext in extends :
                                extendHtml.append("[page:{0}] &rarr;".format(ext))
                        interFacekindString = child['kindString']
                        if interfaceHtml.find('<h4>Constructor</h4>') > 0 :
                            html.append('		<h3 id="{0}" class="dummy-class">{2} [page:{0} {0}] <i class="modifier modifier-interface">{1}</i></h3>'.format(mChildName, interFacekindString, " ".join(extendHtml)))
                            html.append('		<p class="desc">\n\t\t\tSee the [page:{0} {0}] page for more details.\n\t\t</p>'.format(mChildName))
                        else :
                            html.append('		<h3 id="{0}">{2} {0} <i class="modifier modifier-interface">{1}</i></h3>'.format(mChildName, interFacekindString, " ".join(extendHtml)))
                            html.append(interfaceHtml)
                        html.append('')
                        html.append('		<p class="desc">\n\t\t\t{0}\n\t\t</p>'.format(getComment(child)))
                        html.append('')
                    # refTypes.append(typeName)
        nameSpace = className
    elif kindString == "Class" or kindString == "Interface":
        extends = getExtends(info)
        if len(extends) > 0 :
            extendHtml = []
            for ext in extends :
                extendHtml.append("[page:{0}] &rarr;".format(ext))
            html.append('		' + " ".join(extendHtml))
            html.append('')
        html.append('		<h1>{0}</h1>'.format(className))
        html.append('')
        html.append('		<p class="desc">\n\t\t\t{0}\n\t\t</p>'.format(getComment(info, True)))
        html.append('')


        methodCnt = 0
        if 'children' in info :
            if isDecorators(info, 'Component') :
                decorators = info['decorators']
                for deco in decorators :
                    name = deco['name']
                    if name == 'Component' :
                        selector = re.compile("selector: '([a-z0-9\-]+)'")
                        matches = selector.findall(deco['arguments']['obj'])
                        if matches :
                            tagName = matches[0]
                            html.append('		<h2>Angular Template</h2>'.format(deco['name']))
                            html.append('		<code data-type="html">&lt;{0}'.format(tagName))
                            for child in info['children'] :        
                                kindString = child['kindString']
                                paramType = getParamTypes(child)
                                if kindString == 'Property' :
                                    attrName = child['name']
                                    shortText = ''
                                    if 'comment' in child and 'shortText' in child['comment'] :
                                        shortText = child['comment']['shortText'].replace('\t',' ').replace('\n',' ').replace('   ',' ').replace('  ',' ').replace('  ',' ').strip()
                                        if shortText != '' and len(shortText) > 30:
                                            shortText = shortText[0:30] + '...'
                                        if shortText != '' :
                                            shortText = ' -- {0} '.format(shortText) 
                                    if isDecorators(child, 'Input') :
                                        html.append('			[ {0} ]="... {1}{2}"'.format(attrName, paramType, shortText))
                                    elif isDecorators(child, 'Output') :
                                        typeArguments = 'any'
                                        if 'type' in child and 'typeArguments' in child['type'] and len(child['type']['typeArguments']) > 0 :
                                            typeArguments = child['type']['typeArguments'][0]['name']
                                        html.append('			( {0} )="...($event : {1}{2})"'.format(attrName, typeArguments, shortText))
                            html.append('		&gt;&lt;/{0}&gt;'.format(tagName))
                            html.append('		</code>')
                            html.append('')
            htmlConstructor = []
            for child in info['children'] :        
                sources = getSourceFile(child)
                kindString = child['kindString']
                flags = child['flags']
                if (kindString == 'Constructor'):
                    params = []
                    returnType  = 'void' 
                    comment = None
                    paramsComments = []
                    funcModifier = []
                    if 'isPublic' in flags and flags['isPublic'] :
                        funcModifier.append('<i class="modifier modifier-public">Public</i>')
                    elif 'isPrivate' in flags and flags['isPrivate'] :
                        funcModifier.append('<i class="modifier modifier-private">Private</i>')
                    if 'isProtected' in flags and flags['isProtected'] :
                        funcModifier.append('<i class="modifier modifier-protected">Protected</i>')
                    if 'isStatic' in flags and flags['isStatic'] :
                        funcModifier.append('<i class="modifier modifier-static">Static</i>')
                    if 'overwrites' in child :
                        funcModifier.append('<i class="modifier modifier-overwrite">Overwrite</i>')
                    if 'inheritedFrom' in child :
                        funcModifier.append('<i class="modifier modifier-inherited">Inherited</i>')
                    funcModifierStr = ' '.join(funcModifier)
                    if 'signatures' in child :
                        for signatures in child['signatures'] :
                            returnType = getReturnType(signatures)
                            comment = getComment(signatures)
                            if 'parameters' in signatures :
                                params = []
                                paramsComments = []
                                for parameters in signatures['parameters'] :
                                    typeName = getParamTypes(parameters)
                                    isOptional = ''
                                    paramComment = ''
                                    isOptionalComment = ''
                                    if 'flags' in parameters and 'isOptional' in parameters['flags'] and  parameters['flags']['isOptional'] :
                                        isOptional = '?'
                                        isOptionalComment = '(optional) '
                                    if 'comment' in parameters and 'shortText' in parameters['comment'] :
                                        paramComment = getCommentParse(parameters['comment']['shortText'].strip())
                                    params.append(" [param:{0} {1}]{2}".format(typeName, parameters['name'], isOptional)); 
                                    refTypes.append(typeName)
                                    if paramComment == '' :
                                        paramComment = "The {0}.".format(camel2SnameSpace(parameters['name']))
                                    defaultValue = ''
                                    if 'defaultValue' in parameters and parameters['defaultValue'] != 'null':
                                        defaultValue = ' &nbsp; = {0} '.format(parameters['defaultValue'])
                                        
                                    paramsComments.append("[parameter:{0} {1}]{4} - {2}{3}".format(typeName, parameters['name'], isOptionalComment, paramComment, defaultValue)); 
                    htmlConstructor.append('		<h3>[constructor:{1} {0}]( {2} ){3}</h3>'.format(
                        className, 
                        returnType,
                        ", ".join(params),
                        funcModifierStr
                    ))
                    if len(paramsComments) > 0 :
                        htmlConstructor.append('		<h4>Parameters</h4>\n\t\t<p>\n\t\t\t{0}\n\t\t</p>'.format("<br />\n\t\t\t".join(paramsComments)))
                    if comment is not None :
                        htmlConstructor.append('		<p>\n\t\t\t{0}\n\t\t</p>'.format(comment))
                    htmlConstructor.append('')
                    methodCnt += 1
                    break
            if len(htmlConstructor) > 0 :
                html.append('		<h2>Constructor</h2>')
                html.append('		{0}'.format("\n".join(htmlConstructor)))

            if "children" in info:
                htmlProperty = []
                inputCnt = 0
                if len(extends) > 0 :
                    for ext in extends :
                        htmlProperty.append('		<p>')
                        htmlProperty.append('			See the base [page:{0} {0}] class for common properties.'.format(ext))
                        htmlProperty.append('		</p>')
                        inputCnt += 1
                    htmlProperty.append('')
                for child in info['children'] :        
                    sources = getSourceFile(child)
                    kindString = child['kindString']
                    flags = child['flags']
                    if child['name'].startswith('_') :
                        pass
                    if kindString == 'Property' and (parentkindString == "Interface" or isDecorators(child, 'Input') or isDecorators(child, 'Output') or ('isPublic' in flags and flags['isPublic']) or ('isProtected' in flags and flags['isProtected'])):
                        typeName = getParamTypes(child)
                        isOptional = ''
                        funcModifier = []
                        if isDecorators(child, 'Input') :
                            funcModifier.append('<i class="modifier modifier-input">Input</i>')
                        if isDecorators(child, 'Output') :
                            funcModifier.append('<i class="modifier modifier-output">Output</i>')
                        if 'isPublic' in flags and flags['isPublic'] :
                            funcModifier.append('<i class="modifier modifier-public">Public</i>')
                        elif 'isPrivate' in flags and flags['isPrivate'] :
                            funcModifier.append('<i class="modifier modifier-private">Private</i>')
                        if 'isProtected' in flags and flags['isProtected'] :
                            funcModifier.append('<i class="modifier modifier-protected">Protected</i>')
                        if 'isStatic' in flags and flags['isStatic'] :
                            funcModifier.append('<i class="modifier modifier-static">Static</i>')
                        if 'inheritedFrom' in child :
                            funcModifier.append('<i class="modifier modifier-inherited">Inherited</i>')
                        if 'flags' in child and 'isOptional' in child['flags'] and  child['flags']['isOptional'] :
                            isOptional = '?'
                            funcModifier.append('<i class="modifier modifier-optional">Optional</i>')
                        funcModifierStr = ' '.join(funcModifier)
                        defaultValue = ''
                        if 'defaultValue' in child and child['defaultValue'] != 'null':
                            defaultValue = ' &nbsp; = {0} '.format(child['defaultValue'])
                        htmlProperty.append('		<h3>[property:{1} {0}]{2}{4}{3}</h3>'.format(
                            child['name'], 
                            typeName,
                            isOptional,
                            funcModifierStr,
                            defaultValue
                        ))
                        refTypes.append(typeName)
                        htmlProperty.append('		<p>\n\t\t\t{0}\n\t\t</p>'.format(getComment(child)))
                        htmlProperty.append('')
                        inputCnt += 1
                if len(htmlProperty) > 0 :
                    html.append('		<h2>Properties</h2>')
                    html.append('		{0}'.format('\n'.join(htmlProperty)))
                    html.append('')
                htmlMethod = []
                methodCnt = 0
                if len(extends) > 0 :
                    for ext in extends :
                        htmlMethod.append('		<p>')
                        htmlMethod.append('			See the base [page:{0} {0}] class for common methods.'.format(ext))
                        htmlMethod.append('		</p>')
                        methodCnt += 1
                    htmlMethod.append('')
                for child in info['children'] :        
                    sources = getSourceFile(child)
                    kindString = child['kindString']
                    flags = child['flags']
                    if (kindString == 'Method') and (
                        parentkindString == "Interface" or ('isPublic' in flags and flags['isPublic']) or ('isProtected' in flags and flags['isProtected'])) :
                        params = []
                        returnType  = 'void' 
                        comment = None
                        paramsComments = []
                        funcModifier = []
                        if 'isPublic' in flags and flags['isPublic'] :
                            funcModifier.append('<i class="modifier modifier-public">Public</i>')
                        elif 'isPrivate' in flags and flags['isPrivate'] :
                            funcModifier.append('<i class="modifier modifier-private">Private</i>')
                        if 'isProtected' in flags and flags['isProtected'] :
                            funcModifier.append('<i class="modifier modifier-protected">Protected</i>')
                        if 'isStatic' in flags and flags['isStatic'] :
                            funcModifier.append('<i class="modifier modifier-static">Static</i>')
                        if 'overwrites' in child :
                            funcModifier.append('<i class="modifier modifier-overwrite">Overwrite</i>')
                        if 'inheritedFrom' in child :
                            funcModifier.append('<i class="modifier modifier-inherited">Inherited</i>')
                        funcModifierStr = ' '.join(funcModifier)
                        if 'signatures' in child :
                            for signatures in child['signatures'] :
                                returnType = getReturnType(signatures)
                                comment = getComment(signatures)
                                if 'parameters' in signatures :
                                    for parameters in signatures['parameters'] :
                                        typeName = getParamTypes(parameters)
                                        isOptional = ''
                                        paramComment = ''
                                        isOptionalComment = ''
                                        if 'flags' in parameters and 'isOptional' in parameters['flags'] and  parameters['flags']['isOptional'] :
                                            isOptional = '?'
                                            isOptionalComment = '(optional) '
                                        if 'comment' in parameters and 'shortText' in parameters['comment'] :
                                            paramComment = getCommentParse(parameters['comment']['shortText'].strip())
                                        params.append(" [param:{0} {1}]{2}".format(typeName, parameters['name'], isOptional)); 
                                        refTypes.append(typeName)
                                        if paramComment == '' :
                                            paramComment = "The {0}.".format(camel2SnameSpace(parameters['name']))
                                        paramsComments.append("[parameter:{0} {1}] - {2}{3}".format(typeName, parameters['name'], isOptionalComment, paramComment)); 
                        htmlMethod.append('		<h3>[method:{1} {0}]( {2} ){3}</h3>'.format(
                            child['name'], 
                            returnType,
                            ", ".join(params),
                            funcModifierStr
                        ))
                        if len(paramsComments) > 0 :
                            htmlMethod.append('		<h4>Parameters</h4>\n\t\t<p>\n\t\t\t{0}\n\t\t</p>'.format("<br />\n\t\t\t".join(paramsComments)))
                        if comment is not None :
                            htmlMethod.append('		<p>\n\t\t\t{0}\n\t\t</p>'.format(comment))
                        htmlMethod.append('')
                        methodCnt += 1
                if len(htmlMethod) > 0 :
                    html.append('		<h2>Methods</h2>')
                    html.append('		{0}'.format('\n'.join(htmlMethod)))
                    html.append('')
    else :
        pass
        # print(kindString)
        # print(info)

    if 'sources' in info :
        sourcesPath = info['sources'][0]['fileName']
        refClassList = getSameSourceFile(refTypes, nameSpace)
        interfaceHtmlLine = []
        for mchild in refClassList :
            extends = getExtends(mchild)
            interfaceHtml = getExtraInterFace(mchild, extends)
            if interfaceHtml is not None and len(interfaceHtml) > 0 :
                mChildName = mchild['name']
                extendHtml = []
                if len(extends) > 0 :
                    for ext in extends :
                        extendHtml.append("[page:{0}] &rarr;".format(ext))
                interFacekindString = mchild['kindString']
                interfaceHtmlLine.append('		<h3 id="{0}" class="interface">{2} {0} <i class="modifier modifier-interface">{1}</i></h3>'.format(mChildName, interFacekindString, " ".join(extendHtml)))
                interfaceHtmlLine.append(interfaceHtml)
                interfaceHtmlLine.append('')
                interfaceHtmlLine.append('		<p class="desc">\n\t\t\t{0}\n\t\t</p>'.format(getComment(mchild)))
                interfaceHtmlLine.append('')

        if len(interfaceHtmlLine) > 0 :
            html.append("		<h2>Interfaces</h2>")
            html.append("\n".join(interfaceHtmlLine))
        html.append('		<br /><br />')

        html.append('		<h2>Source</h2>')
        html.append('		<p>[link:https://github.com/outmindkjg/ngx3js-module/tree/master/projects/ngx3js/src/lib{0}.ts {0}.ts]</p>'.format(sourcesPath[3:-3]))
    html.append('	</body>')
    html.append('</html>')
    html = re.sub('<br />[ \t\n]*<br />', r'<br />', "\n".join(html))
    if className == 'TWEEN' :
        saveFile('src/assets/ngxapi/en/{0}.html'.format('TweenMain'),html)
    else :
        saveFile('src/assets/ngxapi/en/{0}.html'.format(className),html)
    return True

def getCommentCode(comment : str, isTop : bool = False) :
    restComment = comment
    restComment = restComment.replace('>','&gt;').replace('<','&lt;').replace('] |',']')
    if isTop :
        restComment = re.sub('#### ([a-zA-Z0-9 ]+)', r'<h3>\1</h3>', restComment)
        restComment = re.sub('### ([a-zA-Z0-9 ]+)', r'<h2>\1</h2>', restComment)
    else :
        restComment = re.sub('#### ([a-zA-Z0-9 ]+)', r'<h5>\1</h5>', restComment)
        restComment = re.sub('### ([a-zA-Z0-9 ]+)', r'<h4>\1</h4>', restComment)
    if restComment is not None and restComment.find("```") > -1 :
        whileCnt = 0
        while restComment.find("```") > -1 and whileCnt < 5:
            whileCnt += 1
            start = restComment.find("```")
            end = restComment.find("```", start + 5)
            blockType = 'text'
            conStart = start + 3
            if restComment[conStart: conStart+2] == 'ts' :
                conStart += 2
                blockType = 'typescript'
            elif restComment[conStart: conStart+4] == 'html' :
                conStart += 4
                blockType = 'html'
            elif restComment[conStart: conStart+4] == 'text' :
                conStart += 4
                blockType = 'text'
            elif restComment[conStart: conStart+3] == 'css' :
                conStart += 3
                blockType = 'css'
            elif restComment[conStart: conStart+4] == 'scss' :
                conStart += 4
                blockType = 'scss'
            elif restComment[conStart: conStart+2] == 'js' :
                conStart += 2
                blockType = 'javascript'
            elif restComment[conStart: conStart+10] == 'javascript' :
                conStart += 10
                blockType = 'javascript'
            planeHtml = restComment[conStart: end]
            planeHtml = planeHtml.replace('>','&gt;')
            planeHtml = planeHtml.replace('<','&lt;')
            restComment = restComment[0: start] + '<code data-type="'+blockType+'">' +  planeHtml + '</code>' + restComment[end + 3:]
        if whileCnt >= 4 : 
            print(restComment)
    return restComment

def getReturnType(signatures) :
    returnType = 'void'
    if 'type' in signatures :
        if 'name' in signatures['type'] :
            returnType = signatures['type']['name']
        elif 'type' in signatures['type'] :
            childType = signatures['type']['type']
            if childType == 'union' and 'types' in signatures['type'] :
                typeNames = []
                for typeInfo in signatures['type']['types'] :
                    if 'name' in typeInfo :
                        typeNames.append('{0}'.format(typeInfo['name']))
                    elif typeInfo['type'] == 'array' and 'elementType' in typeInfo and 'name' in typeInfo['elementType']:
                        typeNames.append('{0}[]'.format(typeInfo['elementType']['name']))
                if len(typeNames) > 0 :
                    returnType = "|".join(typeNames).strip()
            elif childType == 'array' and 'elementType' in signatures['type'] and 'name' in signatures['type']['elementType'] :
                returnType = '{0}[]'.format(signatures['type']['elementType']['name'])

    return returnType


def getComment(info, demoCheck : bool = False) :
    commentHtml = ''
    comment = None
    commentTxt = []
    funcReturns = ''
    shortText = ''
    if "comment" in info :
        comment = info['comment']
    if comment is not None :
        if 'shortText' in comment :
            shortText = getCommentCode(comment['shortText'].strip(), demoCheck) + "\n"
        if 'text' in comment :
            commentTxt.append(getCommentCode(comment['text'].strip(), demoCheck))
        if 'tags' in comment :
            tagHtml = []
            for tags in comment['tags'] :
                if (tags['tag'] == 'deprecated'):
                    tagText = tags['text'].strip()
                    tagHtml.append("deprecated - {0}".format(
                        tagText
                    ))
                if (tags['tag'] == 'see'):
                    tagText = tags['text'].strip()
                    if tagText.endswith(",") : 
                        tagText = tagText[0:-1]
                    threeSelector = re.compile("THREE\.([a-zA-Z0-9]+)")
                    matches = threeSelector.findall(tagText)
                    if matches :
                        tagHtml.append("[page:{0} {0}] - {1}".format(
                            matches[0],
                            tagText
                        ))
                    else :
                        linkSelector = re.compile("{@link (.+)\|(.+)\}")
                        matches = linkSelector.findall(tagText)
                        if matches :
                            linkUrl = matches[0][0].strip()
                            linkName = matches[0][1].strip()
                            if linkUrl.startswith('https://outmindkjg.github.io/ngx3js-doc/#/examples/') : 
                                tagHtml.append("[example:{0} {1}] ".format(
                                    linkUrl[51:],
                                    linkName
                                ))
                            else :
                                tagHtml.append("[link:{0} {1}]".format(
                                    linkUrl,
                                    linkName
                                ))
            if len(tagHtml) > 0 :
                commentTxt.append("")
                commentTxt.append("\n".join(tagHtml).strip())
    if 'type' in info and 'type' in info['type']['type']:
        childType = info['type']['type']
        if childType == 'union' :
            typeNames = []
            for typeInfo in info['type']['types'] :
                if 'name' in typeInfo :
                    typeNames.append('[parameter:{0} {0}]'.format(typeInfo['name']))
                elif typeInfo['type'] == 'array' and 'elementType' in typeInfo and 'name' in typeInfo['elementType']:
                    typeNames.append('[parameter:{0} {0}]'.format(typeInfo['elementType']['name']))
            if len(typeNames) > 0 :
                commentTxt.append("")
                commentTxt.append(" | ".join(typeNames).strip())
        elif childType == 'reflection' and 'declaration' in info['type']:
            declaration = info['type']['declaration']
            if 'indexSignature' in declaration :
                parameters = declaration['indexSignature']['parameters']
                key = parameters[0]['name']
                keyType = parameters[0]['type']['name']
                value = 'any'
                if 'name' in declaration['indexSignature']['type'] :
                    value = declaration['indexSignature']['type']['name']
                commentTxt.append("")
                commentTxt.append(" {{ [ {0} : [page:{1} {1}] ] : [page:{2} {2}] }} ".format(key, keyType, value ))
    funcComment = ''
    if comment is not None :
        if 'returns' in comment :
            funcComment = comment['returns'].strip()
    if funcComment != '' or funcReturns != '':
        commentTxt.append("")
        commentTxt.append("Returns : {0} {1}".format(funcComment, funcReturns ))
    if len(commentTxt) == 0 :
        commentTxt.append(shortText)
        shortText = ''
    if len(commentTxt) > 0 :
        commentHtml = "\n".join(commentTxt)
        commentHtml = commentHtml.replace("_@Component","@Component").replace("_@Directive","@Directive").replace("_@Pipe","@Pipe")
        commentHtml = commentHtml.replace("<br>","").replace("<br/>","").replace("<br />","")
        commentHtml = getCommentParse(commentHtml.replace("\n\n\n","\n\n"))
        if demoCheck :
            previewSelector = re.compile("\[example:([A-Za-z/_0-9]+) ([^\]]+)\]")
            matches = previewSelector.findall(commentHtml)
            if matches :
                linkUrl = matches[0][0].strip()
                linkName = matches[0][1].strip()
                commentHtml =  shortText + '\n<h3>Preview - {0}</h3>\n<iframe src="#/viewer/{1}"></iframe>\n\n'.format(linkName, linkUrl) + commentHtml
            else :
                commentHtml =  shortText + commentHtml
        else :
            commentHtml =  shortText + commentHtml
        commentHtml = getCommentParse(commentHtml)
        commentHtml = commentHtml.strip().replace("\n","<br />\n\t\t\t").strip()
    return commentHtml


def getSameSourceFile(refList, nameSpace = None) :
    list = []
    refListChecked = {}
    for txt in refList :
        txtList = txt.split('|')
        for s in txtList :
            if s.endswith('[]') :
                s = s[0:-2]
            if s not in refListChecked:
                if len(s) > 3 and not s.endswith('Component') and not s.endswith('Service') and not s.endswith('Pipe') and not s.endswith('Directive') :
                    if s != 'SimpleChanges' and s != 'EventEmitter' and s != 'True' and s != 'Subscription' and s != 'string' and s != 'boolean' and s != 'number' and s != 'any':
                        refListChecked[s] = False
    nameSpaceApi = []
    if nameSpace is None or nameSpace == '' :
        nameSpaceApi = simpleApi
    else :
        for info in simpleApi :
            if 'children' in info and info['name'] == nameSpace :
                nameSpaceApi = info['children']
    for info in nameSpaceApi :
        name = info["name"]
        if name in refListChecked and not refListChecked[name] :
            list.append(info)
            refListChecked[name] = True
    for info in simpleApi :
        name = info["name"]
        if name in refListChecked and not refListChecked[name]:
            list.append(info)
            refListChecked[name] = True
    for info in i3JSApi :
        name = info["name"]
        if name in refListChecked and not refListChecked[name]:
            list.append(info)
            refListChecked[name] = True
    return list

def getParamTypes(child) :
    typeName = 'any'
    if 'type' in child and 'type' in child['type']:
        childType = child['type']['type']
        if childType == 'union' :
            typeNames = []
            for typeInfo in child['type']['types'] :
                if 'name' in typeInfo :
                    typeNames.append(typeInfo['name'])
                elif typeInfo['type'] == 'literal' and 'value' in typeInfo:
                    typeNames.append("'{0}'".format(typeInfo['value']))
                elif typeInfo['type'] == 'array' and 'elementType' in typeInfo and 'name' in typeInfo['elementType']:
                    typeNames.append(typeInfo['elementType']['name'] + "[]")
            typeName = '|'.join(typeNames)
            # typeName = 'mixed'
        elif childType == 'array' : 
            if 'elementType' in child['type'] and 'name' in child['type']['elementType'] :
                typeName = child['type']['elementType']['name'] + "[]"
        elif 'name' in child['type']:
            typeName = child['type']['name']
    return typeName.replace('NGX3JS.','').replace('O3JS.','THREE.')

def getExtraInterFace(mchild, extends):
    html = []
    fileName = getSourceFile(mchild)
    kindString = mchild["kindString"]
    intfaceName = mchild["name"]
    if kindString == "Interface" or kindString == 'Enumeration' :
        propertiesCnt = 0
        if "children" in mchild:
            properties = []
            methods = []
            constructorsFunc = [] 
            for child in mchild['children'] :        
                sources = getSourceFile(child)
                kindString = child['kindString']
                if kindString == 'Property' or kindString == 'Enumeration member':
                    if kindString == 'Enumeration member' :
                        typeName = intfaceName
                    else :
                        typeName = getParamTypes(child)
                    isOptional = ''
                    if 'flags' in child and 'isOptional' in child['flags'] and  child['flags']['isOptional'] :
                        isOptional = '?'
                    paramComment = getComment(child, False)
                    if paramComment is None or paramComment == '' :
                        paramComment = ' The {0}.'.format(camel2SnameSpace(child['name']))
                    defaultValue = ''
                    if 'defaultValue' in child :
                        defaultValue = ' = {0}'.format(child['defaultValue'])
                    properties.append('[property:{1} {0}]{2}{4} - {3}'.format(
                        child['name'], 
                        typeName,
                        isOptional,
                        paramComment,
                        defaultValue
                    ))
                    propertiesCnt += 1
                elif kindString == 'Method' or kindString == 'Constructor' :
                    params = []
                    returnType  = 'void' 
                    comment = None
                    methodsProperties = []
                    for signatures in child['signatures'] :
                        returnType = getReturnType(signatures)
                        comment = getComment(signatures)
                        if 'parameters' in signatures :
                            for parameters in signatures['parameters'] :
                                typeName = getParamTypes(parameters)
                                isOptional = ''
                                if 'flags' in parameters and 'isOptional' in parameters['flags'] and  parameters['flags']['isOptional'] :
                                    isOptional = '?'
                                params.append(" [param:{0} {1}]{2}".format(typeName, parameters['name'], isOptional)); 
                                paramComment = getComment(parameters)
                                if paramComment is None or paramComment == '' :
                                    paramComment = ' The {0}.'.format(camel2SnameSpace(parameters['name']))
                                methodsProperties.append('[property:{1} {0}]{2} - {3}'.format(
                                    parameters['name'], 
                                    typeName,
                                    isOptional,
                                    paramComment
                                ))
                        childName = child['name']
                        if childName == '__type':
                            childName = 'function'
                        if comment is not None and len(comment) > 1:
                            comment = '- ' + comment
                        if kindString == 'Constructor' :
                            constructorsFunc.append('[constructor:{1} {0}]( {2} ) {3}'.format(
                                returnType, 
                                returnType,
                                ", ".join(params),
                                comment
                            ))
                        else :
                            methods.append('[method:{1} {0}]( {2} ) {3}'.format(
                                childName, 
                                returnType,
                                ", ".join(params),
                                comment
                            ))
            if len(constructorsFunc) > 0 :
                html.append('		<h4>Constructor</h4>')
                html.append('		<p>\n\t\t\t{0}\n\t\t</p>'.format('<br />\n\t\t\t'.join(constructorsFunc)))                    
            if len(properties) > 0 :
                html.append('		<h4>Properties</h4>')
                html.append('		<p>\n\t\t\t{0}\n\t\t</p>'.format('<br />\n\t\t\t'.join(properties)))                    
            if len(methods) > 0 :
                html.append('		<h4>Methods</h4>')
                html.append('		<p>\n\t\t\t{0}\n\t\t</p>'.format('<br />\n\t\t\t'.join(methods)))                    
    elif kindString == "Type alias" or kindString == 'Variable':
        typeInfo = mchild['type']
        typeName = typeInfo['type']
        if typeName == 'reflection' :
            params = []
            returnType  = 'void' 
            comment = None
            child = typeInfo['declaration']
            if 'signatures' in child :
                for signatures in child['signatures'] :
                    returnType = getReturnType(signatures)
                    comment = getComment(signatures)
                    properties = []
                    if 'parameters' in signatures :
                        for parameters in signatures['parameters'] :
                            typeName = getParamTypes(parameters)
                            isOptional = ''
                            if 'flags' in parameters and 'isOptional' in parameters['flags'] and  parameters['flags']['isOptional'] :
                                isOptional = '?'
                            params.append(" [param:{0} {1}]{2}".format(typeName, parameters['name'], isOptional)); 
                            paramComment = getComment(parameters)
                            if paramComment is None or paramComment == '' :
                                paramComment = ' The {0}.'.format(camel2SnameSpace(parameters['name']))
                            properties.append('[property:{1} {0}]{2} - {3}'.format(
                                parameters['name'], 
                                typeName,
                                isOptional,
                                paramComment
                            ))
                childName = child['name']
                if childName == '__type':
                    childName = 'function'
                html.append('		<h4>[method:{1} {0}]( {2} )</h4>'.format(
                    childName, 
                    returnType,
                    ", ".join(params)
                ))
                if len(properties) > 0 :
                    html.append('		<h4>Parameters</h4>')
                    html.append('		<p>\n\t\t\t{0}\n\t\t</p>'.format('<br />\n\t\t\t'.join(properties)))
            if 'indexSignature' in child :
                signatures = child['indexSignature']
                returnType = getReturnType(signatures)
                comment = getComment(signatures)
                if 'parameters' in signatures :
                    for parameters in signatures['parameters'] :
                        typeName = getParamTypes(parameters)
                        isOptional = ''
                        if 'flags' in child and 'isOptional' in child['flags'] and  child['flags']['isOptional'] :
                            isOptional = '?'
                        params.append(" [param:{0} {1}]{2}".format(typeName, parameters['name'], isOptional)); 
                html.append('		<h3> {{ [ {2} ] : [param:{1} emptyName] }}</h3>'.format(
                    child['name'], 
                    returnType,
                    ", ".join(params)
                ))
            
            if comment is not None :
                html.append('		<p>\n\t\t\t{0}\n\t\t</p>'.format(comment))
            html.append('')
        elif typeName == 'union' :
            child = mchild
            typeName = getParamTypes(child)
            html.append('		<h3>[property:{1} {0}]</h3>'.format(
                child['name'], 
                typeName
            ))
        html.append('')
    else :
        print(kindString)
    return "\n".join(html)


def getCommentParse(commentHtml) :
    commentHtml = re.sub('\[([^\]]+)\]\(([^\)]+)\)', r'[link:\2 \1]', commentHtml)
    commentHtml = re.sub('\[link:https://outmindkjg.github.io/ngx3js-doc/#/docs/[a-z0-9\/]+/([a-zA-Z0-9\.]+) ', r'[page:\1 ', commentHtml)
    commentHtml = re.sub('\[link:https://outmindkjg.github.io/ngx3js-doc/#/examples/([a-zA-Z_0-9/\.]+) ', r'[example:\1 ', commentHtml)
    commentHtml = re.sub('\[example:([^\]]+)\] \|', r'[example:\1]', commentHtml)
    commentHtml = re.sub('&lt;em&gt;([^&]+)&lt;/em&gt;', r'<em>\1</em>', commentHtml)
    
    commentHtml = re.sub('\*([^ ]+)\*', r'<i>\1</i>', commentHtml)
    tableSelector = re.compile("\n(.+)\n\|(:|)--.+\|\n.*")
    matches = tableSelector.findall(commentHtml)
    if matches :
        lines = commentHtml.split('\n')
        newLines = []
        headStated = False
        bodyStated = False
        tableLines = []
        for line in lines :
            if line.startswith('|') and line.endswith('|') :
                if not headStated :
                    tableLines = []
                    tableLines.append('<table><thead><tr>{0}</tr></thead><tbody>'.format(re.sub('\|', r'</th><th>', line)))
                    bodyStated = True
                    headStated = True
                elif line.find('---') == -1 :
                    tableLines.append('<tr>{0}</tr>'.format(re.sub('\|', r'</td><td>', line)))
            elif bodyStated :
                bodyStated = False
                headStated = False
                tableLines.append('</table>')
                newLines.append(' '.join(tableLines))
            else :
                newLines.append(line)
        if bodyStated :
            bodyStated = False
            headStated = False
            tableLines.append('</table>')
            newLines.append(re.sub('(<td>|<th>)</tr>','</tr>',re.sub('<tr>(</td>|</th>)','<tr>',' '.join(tableLines))))
        commentHtml = '\n'.join(newLines)
    return commentHtml



# +
# getGenApiDocs("MeshComponent")

# getGenApiDocs("NgxThreeUtil")
getGenApiDocs("I3JS")

# getGenApiDocs("AbstractGeometryComponent")
# getGenApiDocs("GeometryComponent")
# getGenApiDocs("GeometryComponent")
# getGenApiDocs("AudioComponent")
# -



# +

loadedClass = {}
jsonList = []
loadedClassByName = {}

for child in simpleApi :
    name = child["name"]
    kindString = child["kindString"]
    if name not in loadedClass and ( kindString == 'Class' or  kindString == 'Namespace' or kindString == 'Type alias'):
        loadedClass[name] = child['sources'][0]['fileName']
for name in loadedClass :
    url = loadedClass[name]
    if url.startswith('lib/') :
        if getGenApiDocs(name) :
            jsonList.append('"{0}" : "ngxapi/en/{0}"'.format(name))
            urlInfos = url.split('/')
            fileName = urlInfos[-1][0:-3]
            if fileName not in loadedClassByName :
                loadedClassByName[fileName] = []
            loadedClassByName[fileName].append('"{0}" : "ngxapi/en/{0}"'.format(name))
    # else :
    #    print(url)
for name in loadedClassByName :
    print('"{0}" : {{'.format(name))
    print(",\n".join(loadedClassByName[name]))
    print('},\n')

# print(",\n".join(jsonList))

# -





StarcoderdataJupyterScriptsDedupFiltered