# Path: sydpy/component.py
# class Component:
#     """Component class is the base class for all objects that are part of the user 
#     object hierarchy.    
#     """
#     
#     comp = {}
#     __cur_parent_class__ = None
#     
#     def __init__(self, name=None, parent=None, **kwargs):
#         """Instantiate a new compinit
#         
#         name    -- The name of the compinit
#         """
#         self.name = name
#         self._parent = parent
#         if parent is not None:
#             self._parent.comp[name] = self
#         self.comp = {}
# 
# #     @property
# #     def qname(self):
# #         if self.name:
# #             if self._parent:
# #                 return sep.join([self._parent.qname, self.name])
# # 
# #         return self.name
# 
#     def __repr__(self):
#         return self.name
# 
#     def __setitem__(self, key, val):
#         try:
#             val = sydsys().get_config(self.name, key)
#         except KeyError: 
#             pass
#         
#         self.comp[key] = val
#         
#         return val
#     
#     def __getitem__(self, key):
# #         return ddic[sep.join([self.qname, key])]
#         return self.comp[key]
# 
#     def inst(self, name, cls, *args, **kwargs):
#         try:
#             val = sydsys().get_config(self.name, name)
#             if not inspect.isclass(val):
#                 setattr(self, name, val)
#                 return val
#             else:
#                 cls = val
#         except KeyError: 
#             pass
#         
#         
#         if self.name:
#             qname = self.name + '.' + name
#         else:
#             qname = name
#         
#         obj = cls(qname, *args , **kwargs)
#         
#         self.comp[name] = obj
#         
#         return obj
#     
#     def search(self, pattern='*', of_type=None, depth=0, pattern_relative=True):
#         
#         if pattern_relative:
#             if self.name:
#                 pattern = sep.join([self.name, pattern])
# 
#         for _, c in self.comp.items():
#             if fnmatch.fnmatch(c.name, pattern):
#                 if (of_type is None) or isinstance(c, of_type):
#                     yield c
#                     
#                 if depth:
#                     yield from c.search(pattern, pattern_relative=False, depth=depth-1)
# 
# def compinit(func):
# 
#     def wrapper(self, name=None, parent=None, *args, **kwargs):
#         
#         if func.__name__ != '__init__':
#             raise Exception('Decorated function must be __init__().')
# 
#         params = all2kwargs(func, self, *args, name=name, parent=parent, **kwargs)
#         if self.__cur_parent_class__ is None:
#             if (parent is not None) and (name is not None):    
#             
#                 parent[name] = self
#                 qname = sep.join([parent.qname, name])
#                 
#                 sydsys()[qname] = self
#                 
#                 sys_conf = sydsys().get_all_attrs(qname)
#                 
#                 for n, v in sys_conf.items():
#                     params[n] = v
#                     
#     #             arg_names, varargs, varkw, defaults = (
#     #                                                    inspect.getargspec(func))
#     #             
#     #             if defaults:
#     #                 for arg_name, _ in zip(reversed(arg_names), reversed(defaults)):
#     #                     setattr(self, arg_name, params[arg_name])
#         
#             self.__cur_parent_class__ = self.__class__
#             
#         self.__cur_parent_class__ = self.__cur_parent_class__.__bases__[0] 
#         self.__cur_parent_class__.__init__(**params)
# 
#         func(**params)
#         
#     return wrapper
# 
# def sydsys(sid = 0):
#     return _system[sid]


from sydpy.component import Component, compinit, sydsys
from subprocess import Popen, PIPE
import string
import os
import itertools
""")

module_inst_tmpl = string.Template("""
  ${module_name} ${instance_name} (
    ${port_map}
  );
""")

port_map_tmpl = string.Template(".${port_name} (${signal_name})")

def shell(cmd):
    print(' '.join(cmd))
    p = Popen(' '.join(cmd), shell=True, stdout=PIPE, stderr=PIPE, universal_newlines=True)
    out, err = p.communicate()
    print(out.rstrip(), err.rstrip())
    print("Return code: ", p.returncode)
    return out, err, p.returncode

class XsimIntf(Component):

    state_type = {0: "S_STARTED", 1: "S_CONNECTED", 2: "S_INITIALIZED", 3:"S_IMPORT", 4:"S_EXPORT", 5:"S_DELAY"};
    cmds = {'GET_STATE': {'type': 'GET', 'params': ['state']},
            'CONTINUE': {'type': 'CONTINUE', 'params': ['state']}
            }

    @compinit
    def __init__(self, builddir='.', **kwargs):
        self.cosim_pool = []
        sydsys().sim.events['run_start'].append(sydsys().sim_run_start)
        sydsys().sim.events['run_end'].append(sydsys().sim_run_end)

# Path: sydpy/component.py
# class Component:
#     """Component class is the base class for all objects that are part of the user 
#     object hierarchy.    
#     """
#     
#     comp = {}
#     __cur_parent_class__ = None
#     
#     def __init__(self, name=None, parent=None, **kwargs):
#         """Instantiate a new compinit
#         
#         name    -- The name of the compinit
#         """
#         self.name = name
#         self._parent = parent
#         if parent is not None:
#             self._parent.comp[name] = self
#         self.comp = {}
# 
# #     @property
# #     def qname(self):
# #         if self.name:
# #             if self._parent:
# #                 return sep.join([self._parent.qname, self.name])
# # 
# #         return self.name
# 
#     def __repr__(self):
#         return self.name
# 
#     def __setitem__(self, key, val):
#         try:
#             val = sydsys().get_config(self.name, key)
#         except KeyError: 
#             pass
#         
#         self.comp[key] = val
#         
#         return val
#     
#     def __getitem__(self, key):
# #         return ddic[sep.join([self.qname, key])]
#         return self.comp[key]
# 
#     def inst(self, name, cls, *args, **kwargs):
#         try:
#             val = sydsys().get_config(self.name, name)
#             if not inspect.isclass(val):
#                 setattr(self, name, val)
#                 return val
#             else:
#                 cls = val
#         except KeyError: 
#             pass
#         
#         
#         if self.name:
#             qname = self.name + '.' + name
#         else:
#             qname = name
#         
#         obj = cls(qname, *args , **kwargs)
#         
#         self.comp[name] = obj
#         
#         return obj
#     
#     def search(self, pattern='*', of_type=None, depth=0, pattern_relative=True):
#         
#         if pattern_relative:
#             if self.name:
#                 pattern = sep.join([self.name, pattern])
# 
#         for _, c in self.comp.items():
#             if fnmatch.fnmatch(c.name, pattern):
#                 if (of_type is None) or isinstance(c, of_type):
#                     yield c
#                     
#                 if depth:
#                     yield from c.search(pattern, pattern_relative=False, depth=depth-1)
# 
# def compinit(func):
# 
#     def wrapper(self, name=None, parent=None, *args, **kwargs):
#         
#         if func.__name__ != '__init__':
#             raise Exception('Decorated function must be __init__().')
# 
#         params = all2kwargs(func, self, *args, name=name, parent=parent, **kwargs)
#         if self.__cur_parent_class__ is None:
#             if (parent is not None) and (name is not None):    
#             
#                 parent[name] = self
#                 qname = sep.join([parent.qname, name])
#                 
#                 sydsys()[qname] = self
#                 
#                 sys_conf = sydsys().get_all_attrs(qname)
#                 
#                 for n, v in sys_conf.items():
#                     params[n] = v
#                     
#     #             arg_names, varargs, varkw, defaults = (
#     #                                                    inspect.getargspec(func))
#     #             
#     #             if defaults:
#     #                 for arg_name, _ in zip(reversed(arg_names), reversed(defaults)):
#     #                     setattr(self, arg_name, params[arg_name])
#         
#             self.__cur_parent_class__ = self.__class__
#             
#         self.__cur_parent_class__ = self.__cur_parent_class__.__bases__[0] 
#         self.__cur_parent_class__.__init__(**params)
# 
#         func(**params)
#         
#     return wrapper
# 
# def sydsys(sid = 0):
#     return _system[sid]


# Path: sydpy/xsim.py
from sydpy.component import Component, compinit, sydsys
from subprocess import Popen, PIPE
import string
import os
import itertools

""")

module_inst_tmpl = string.Template("""
  ${module_name} ${instance_name} (
    ${port_map}
  );
""")

port_map_tmpl = string.Template(".${port_name} (${signal_name})")

def shell(cmd):
    print(' '.join(cmd))
    p = Popen(' '.join(cmd), shell=True, stdout=PIPE, stderr=PIPE, universal_newlines=True)
    out, err = p.communicate()
    print(out.rstrip(), err.rstrip())
    print("Return code: ", p.returncode)
    return out, err, p.returncode

class XsimIntf(Component):

    state_type = {0: "S_STARTED", 1: "S_CONNECTED", 2: "S_INITIALIZED", 3:"S_IMPORT", 4:"S_EXPORT", 5:"S_DELAY"};
    cmds = {'GET_STATE': {'type': 'GET', 'params': ['state']},
            'CONTINUE': {'type': 'CONTINUE', 'params': ['state']}
            }

    @compinit
    def __init__(self, builddir='.', **kwargs):
        self.cosim_pool = []
        sydsys().sim.events['run_start'].append(sydsys().sim_run_start)
        sydsys().sim.events['run_end'].append(sydsys().sim_run_end)

        sydsys().sim.events['delta_settled'].append(sydsys().sim_delta_settled)