from pylayers.util import project
import pylayers.util.CDF as cdf
import pylayers.signal.bsignal as bs
import pylayers.gis.layout as ly
import pylayers.util.pyutil as pyu
import ConfigParser
import matplotlib.pylab as plt
import itertools
import pickle
import pdb


class Simnet2cir(object):
    """
    Simnet2cir

    This class allows to perform a raytracing simulation from
    a simulnet simulation. First of using it, you MUST have run
    a simulnet simulation.

    Notes
    -----

    1) From your Project directory, configure simulnet.ini save section with:
    Save =['pyray']

    2) Run simulnet

    from pylayers.simul.simulnet import *
    S = Simul()
    S.runsimul()

    3) At the end of the simulnet simulation, a 'netsave' folder has been
    created into your Pylayers project directory. This folder contains
    all required files for Simnet2cir computation

    4) Launch the Raytracing simulation from the pre-computed simulnet
    simulation:

    from pylayers.exploit.simnet import *
    E = Simnet2cir()
    E.compute() #

    5) See CIR results using pltciri or pltcir:

    >>> E.pltcir(1,2,1)
    >>> E.pltciri(1,2)

    """
    def __init__(self,simnetfile='pyray.ini'):
        self.simnetfile=simnetfile
        self.load()

    def load(self):
        """
        Load simulnet_data configuration file
        """
        if not os.path.isfile(pyu.getlong(self.simnetfile,pstruc['DIRNETSAVE'])):
            raise NameError(self.simnetfile +' cannot be reached.\
 Have you launch a simulnet simulation before ? \
 Please use \'>>> Simnet2cir?\' to see help ')
        self.simcfg = ConfigParser.ConfigParser()
        self.simcfg.read(pyu.getlong(self.simnetfile,pstruc['DIRNETSAVE']))
        self.Lfilename = self.simcfg.get('layout','layoutname')
        self.lAG = eval(self.simcfg.get('nodes','ag'))
        self.lAP = eval(self.simcfg.get('nodes','ap'))
        self.uptime = eval(self.simcfg.get('simulation','updatetime'))
        # create a Simul object with the correct layout
        self.S = sime.Simul()
        self.S.layout(self.Lfilename,'matDB.ini','slabDB.ini')
        self.lap = len(self.lAP)
        self.lag = len(self.lAG)

        self.L = self.S.L
        try:
            self.L.dumpr()
            print 'Layout graphs are loaded from ',basename,'/struc'
        except:
        #self.L.sl = sl
        #self.L.loadGr(G1)
            print 'First time your use the Layout.Graphs are curently build, it may take few minutes.'
            self.L.buildGt()
            self.L.dumpw()