import ast
import os,sys,inspect


from HDPython.base import *
from HDPython.HDPython_AST import *
from HDPython.to_v_object import *
from HDPython.primitive_type_converter import get_primitive_hdl_converter



def make_unique_list(list_in):
    uniqueList = []
    for ele in list_in:
        if ele not in uniqueList:
            uniqueList.append(ele)
    return uniqueList


def Fill_AST_Tree(package,SourceFile):
    if not SourceFile:
        return
    package.astTree = xgenAST(SourceFile)

    for x in package.PackageContent:
        if x._issubclass_("v_class"):
            fun= package.astTree.extractFunctionsForClass(x ,package )
            x.__hdl_converter__.__ast_functions__ += fun

        if x._issubclass_("v_free_function_template"):
            fun= package.astTree.extractFreeFunctions(x ,package )
            x.__hdl_converter__.__ast_functions__ += fun
    
    x.__hdl_converter__.__ast_functions__ = make_unique_list(x.__hdl_converter__.__ast_functions__)

    
class v_package(HDPython_base):
    def __init__(self, PackageName,PackageContent, sourceFile=None):
        super().__init__()
        self.__hdl_converter__ =  get_primitive_hdl_converter("v_package" )() 
        
        s = isConverting2VHDL()
        set_isConverting2VHDL(True)
        proc = isProcess()
        set_isProcess(True)
        self.PackageName = PackageName
        self.PackageContent = PackageContent
        self.astTree = None
        self.astv_classes = None
        Fill_AST_Tree(self, sourceFile)

        set_isConverting2VHDL(s)
        set_isProcess(proc)
            
    





   

    def getName(self):
        return type(self).__name__
    def to_string(self):
        s = isConverting2VHDL()
        set_isConverting2VHDL(True)
        
        
        hdl.parse_file(self)
        
        
        ret = "-- XGEN: Autogenerated File\n\n"
        ret += hdl.def_includes(self, None, self)
        ret += "\n\n"
        p_header = hdl.def_packet_header(self,None, self)
        if p_header.strip():
            ret += "package " + self.PackageName + " is \n\n"
            ret += p_header
            ret += "end " + self.PackageName + ";\n\n\n"

            ret += "package body "+ self.PackageName +" is\n\n"
            ret += hdl.def_packet_body(self,None, self)
            ret += "end "+ self.PackageName +";\n\n"
        


        set_isConverting2VHDL(s)
        return ret

    def getInstantByName(self,SymbolName):
        for t  in self.PackageContent:
            t = to_v_object(t)
            if t._type == SymbolName:
                return t


        return None

    def append(self, obj):
        self.PackageContent.append(obj)
