# -*- coding: utf-8 -*-
# generated by wxGlade 0.6.3 on Mon May 18 09:43:57 2009

import wx
import os
from formTank import formTank
from formJunction import formJunction
from formCylinder import formCylinder
from formAtmosphere import formAtmosphere
from formSimulation import formSimulation
from formTube import formTube
from formValve import formValve
from Help import Help
from About import About
from PostProcess import PostProcess
import default_values
from extraFunctions import *
import wx.lib.ogl as ogl
from MyEvtHandler import MyEvtHandler,MyLineEvtHandler,keyMap
from MyShapeCanvas import MyShapeCanvas
import time

# begin wxGlade: dependencies
# end wxGlade

# begin wxGlade: extracode

# end wxGlade

class Home(wx.Frame):
    Simulator = []
    Cylinders = []
    Tanks = []
    Junctions = []
    Tubes = []
    Valves = []
    Atmospheres = []
    shapes = []
    connectionLines = []
    stateFromFile = 0
    thisFile = 'untitled.py'
    copyboard = ''
    saved = 1
    calcEngine = 1
    pathCode = "../ICESym-1D/src/"
    # pathTests = "../ICESym-1D/src/"
    pathTests = "./"
    names = ['Cylinders', 'Tubes', 'Tanks', 'Valves', 'Junctions', 'Atmospheres']
    itemsTree = dict()
    def __init__(self, style, *args, **kwds):
        # begin wxGlade: Home.__init__
        style = wx.DEFAULT_FRAME_STYLE
        wx.Frame.__init__(self, *args, **kwds)
        self.window_1 = wx.SplitterWindow(self, -1, style=wx.SP_3DBORDER|wx.SP_BORDER|wx.SP_LIVE_UPDATE|wx.WANTS_CHARS)
        self.window_1_pane_2 = wx.ScrolledWindow(self.window_1, -1, style=wx.TAB_TRAVERSAL|wx.WANTS_CHARS)
        self.window_1_pane_1 = wx.ScrolledWindow(self.window_1, -1, style=wx.TAB_TRAVERSAL|wx.WANTS_CHARS)
        icono = wx.EmptyIcon()
        icono.CopyFromBitmap(wx.Image("images/icesIcone.png",wx.BITMAP_TYPE_PNG).ConvertToBitmap())
        self.SetIcon(icono) 
        
        # Menu Bar
        self.home_menubar = wx.MenuBar()
        self.File = wx.Menu()
        self.FileOpen = wx.MenuItem(self.File, wx.ID_OPEN, "Open", "Load another simulation", wx.ITEM_NORMAL)
        self.File.AppendItem(self.FileOpen)
        self.FileSave = wx.MenuItem(self.File, wx.ID_SAVE, "Save", "Save this simulation with the actual name", wx.ITEM_NORMAL)
        self.File.AppendItem(self.FileSave)
        self.FileSaveAs = wx.MenuItem(self.File, wx.ID_SAVEAS, "Save As...", "Save this simulation with the another name", wx.ITEM_NORMAL)
        self.File.AppendItem(self.FileSaveAs)
        #Export = wx.Menu()
        #self.pythonScript = wx.MenuItem(Export, 15, "as python Script", "", wx.ITEM_NORMAL)
        #Export.AppendItem(self.pythonScript)
        #self.File.AppendMenu(wx.NewId(), "Export...", Export, "")
        self.FileClose = wx.MenuItem(self.File, wx.ID_CLOSE, "Close", "Close this simulation and start other new", wx.ITEM_NORMAL)
        self.File.AppendItem(self.FileClose)
        self.FileExit = wx.MenuItem(self.File, wx.ID_EXIT, "Exit", "Exit Simulator", wx.ITEM_NORMAL)
        self.File.AppendItem(self.FileExit)
        self.home_menubar.Append(self.File, "File")

        self.Edit = wx.Menu()
        self.EditCopy = wx.MenuItem(self.Edit, wx.ID_COPY, "Copy", "Copy the selected object", wx.ITEM_NORMAL)
        self.Edit.AppendItem(self.EditCopy)
        self.EditPaste = wx.MenuItem(self.Edit, wx.ID_PASTE, "Paste", "Paste the object in clipboard", wx.ITEM_NORMAL)
        self.Edit.AppendItem(self.EditPaste)
        self.EditDelete = wx.MenuItem(self.Edit, wx.ID_DELETE, "Delete", "Delete the object in clipboard", wx.ITEM_NORMAL)
        self.Edit.AppendItem(self.EditDelete)
        self.home_menubar.Append(self.Edit, "Edit")

        self.Simulation = wx.Menu()
        self.SimulationConfigure = wx.MenuItem(self.Simulation, 20, "Configure...", "Configure this Simulation", wx.ITEM_NORMAL)
        self.Simulation.AppendItem(self.SimulationConfigure)
        self.SimulationRun = wx.MenuItem(self.Simulation, 21, "Run", "Run Simulation", wx.ITEM_NORMAL)
        self.Simulation.AppendItem(self.SimulationRun)
        self.SimulationPost = wx.MenuItem(self.Simulation, 22, "Post Process", "Post Process", wx.ITEM_NORMAL)
        self.Simulation.AppendItem(self.SimulationPost)
        self.home_menubar.Append(self.Simulation, "Simulation")
        self.Components = wx.Menu()
        New = wx.Menu()
        self.Junction = wx.MenuItem(New, 40, "Junction", "Add new Junction to simulation", wx.ITEM_NORMAL)
        New.Append(self.Junction)
        self.Tank = wx.MenuItem(New, 41, "Tank", "Add new Tank to simulation", wx.ITEM_NORMAL)
        New.Append(self.Tank)
        self.Cylinder = wx.MenuItem(New, 42, "Cylinder", "Add new Cylinder to Simulation", wx.ITEM_NORMAL)
        New.Append(self.Cylinder)
        self.Tube = wx.MenuItem(New, 43, "Tube", "Add new Tube to Simulation", wx.ITEM_NORMAL)
        New.Append(self.Tube)
        self.Atmosphere = wx.MenuItem(New, 44, "Atmosphere", "Add new Atmosphere to simulation", wx.ITEM_NORMAL)
        New.Append(self.Atmosphere)
        self.Valve = wx.MenuItem(New, 45, "Valve", "New Valve", wx.ITEM_NORMAL)
        New.Append(self.Valve)
        self.Components.AppendMenu(wx.NewId(), "New", New, "")
        self.home_menubar.Append(self.Components, "Components")
        self.Help = wx.Menu()
        self.About = wx.MenuItem(self.Help, 30, "About", "About ICESym-GUI", wx.ITEM_NORMAL)
        self.UserHelp = wx.MenuItem(self.Help, 31, "User Help [F1]", "Help ICESym-GUI", wx.ITEM_NORMAL)
        self.Help.AppendItem(self.UserHelp)
        self.Help.AppendItem(self.About)
        self.home_menubar.Append(self.Help, "Help")
        self.SetMenuBar(self.home_menubar)
        # Menu Bar end
        self.home_statusbar = self.CreateStatusBar(1, 0)

        # Tool Bar
        self.home_toolbar = wx.ToolBar(self, -1)
        self.SetToolBar(self.home_toolbar)
        self.home_toolbar.AddTool(1, "Tube", wx.Bitmap("images/TubesIconeSmall.bmp", wx.BITMAP_TYPE_ANY), wx.NullBitmap, wx.ITEM_NORMAL, "New Tube", "Add new Tube to Simulation")
        self.home_toolbar.AddTool(2, "Cylinder", wx.Bitmap("images/CylindersIconeSmall.bmp", wx.BITMAP_TYPE_ANY), wx.NullBitmap, wx.ITEM_NORMAL, "New Cylinder", "Add new Cylinder to Simulation")
        self.home_toolbar.AddTool(3, "Junction", wx.Bitmap("images/JunctionsIconeSmall.bmp", wx.BITMAP_TYPE_ANY), wx.NullBitmap, wx.ITEM_NORMAL, "New Junction", "Add new Junction to simulation")
        self.home_toolbar.AddTool(4, "Tank", wx.Bitmap("images/TanksIconeSmall.bmp", wx.BITMAP_TYPE_ANY), wx.NullBitmap, wx.ITEM_NORMAL, "New Tank", "Add new Tank to simulation")
        self.home_toolbar.AddTool(5, "Atmosphere", wx.Bitmap("images/AtmospheresIconeSmall.bmp", wx.BITMAP_TYPE_ANY), wx.NullBitmap, wx.ITEM_NORMAL, "New Atmosphere", "Add new Atmosphere to simulation")
        self.home_toolbar.AddTool(6, "Valve", wx.Bitmap("images/ValvesIntakeIconeSmall.bmp", wx.BITMAP_TYPE_ANY), wx.NullBitmap, wx.ITEM_NORMAL, "New Valve", "")

        # Tool Bar end
        #self.canvas = ogl.ShapeCanvas(self.window_1_pane_2, -1)
        self.canvas = MyShapeCanvas(self,self.window_1_pane_2, -1)
        #self.tree = wx.TreeCtrl(self.window_1_pane_1,-1, wx.DefaultPosition, wx.DefaultSize,wx.TR_HAS_BUTTONS|wx.TR_HIDE_ROOT)
        self.tree = wx.TreeCtrl(self.window_1_pane_1, -1, wx.DefaultPosition, wx.DefaultSize, wx.TR_HAS_BUTTONS)
       
        isz = (16,16)
        il = wx.ImageList(isz[0], isz[1])
        self.fldridx     = il.Add(wx.ArtProvider.GetBitmap(wx.ART_FOLDER,      wx.ART_OTHER, isz))
        self.fldropenidx = il.Add(wx.ArtProvider.GetBitmap(wx.ART_FILE_OPEN,   wx.ART_OTHER, isz))
        self.fileidx     = il.Add(wx.ArtProvider.GetBitmap(wx.ART_NORMAL_FILE, wx.ART_OTHER, isz))
        self.tipdx         = il.Add(wx.ArtProvider.GetBitmap(wx.ART_TIP,   wx.ART_OTHER, isz))
        #smileidx    = il.Add(images.Smiles.GetBitmap())

        self.tree.SetImageList(il)
        self.il = il

        # NOTE:  For some reason tree items have to have a data object in
        #        order to be sorted.  Since our compare just uses the labels
        #        we don't need any real data, so we'll just use None below for
        #        the item data.

        self.root = self.tree.AddRoot("The Root Item")
        self.tree.SetItemData(self.root, None)
        self.tree.SetItemImage(self.root, self.fldridx, wx.TreeItemIcon_Normal)
        self.tree.SetItemImage(self.root, self.fldropenidx, wx.TreeItemIcon_Expanded)
  
        self.initTree()

        self.tree.Expand(self.root)

        self.__set_properties()
        self.__do_layout()

        self.Bind(wx.EVT_MENU, self.OnMenuFileOpen, self.FileOpen)
        self.Bind(wx.EVT_MENU, self.OnMenuFileSave, self.FileSave)
        self.Bind(wx.EVT_MENU, self.OnMenuFileSaveAs, self.FileSaveAs)
        #self.Bind(wx.EVT_MENU, self.onExportPythonScript, self.pythonScript)
        self.Bind(wx.EVT_MENU, self.OnMenuFileClose, self.FileClose)
        self.Bind(wx.EVT_MENU, self.OnMenuFileExit, self.FileExit)
        self.Bind(wx.EVT_MENU, self.OnMenuEditCopy, self.EditCopy)
        self.Bind(wx.EVT_MENU, self.OnMenuEditPaste, self.EditPaste)
        self.Bind(wx.EVT_MENU, self.OnMenuEditDelete, self.EditDelete)
        self.Bind(wx.EVT_MENU, self.OnMenuSimulationConfigure, self.SimulationConfigure)
        self.Bind(wx.EVT_MENU, self.OnMenuSimulationRun, self.SimulationRun)
        self.Bind(wx.EVT_MENU, self.OnMenuSimulationPost, self.SimulationPost)
        self.Bind(wx.EVT_MENU, self.OnStatusBarJunction, self.Junction)
        self.Bind(wx.EVT_MENU, self.OnStatusBarTank, self.Tank)
        self.Bind(wx.EVT_MENU, self.OnStatusBarCylinder, self.Cylinder)
        self.Bind(wx.EVT_MENU, self.OnStatusBarTube, self.Tube)
        self.Bind(wx.EVT_MENU, self.OnStatusBarAtmosphere, self.Atmosphere)
        self.Bind(wx.EVT_MENU, self.OnStatusBarValve, self.Valve)
        self.Bind(wx.EVT_MENU, self.OnMenuUserHelp, self.UserHelp)
        self.Bind(wx.EVT_MENU, self.OnMenuHelpAbout, self.About)
        self.Bind(wx.EVT_TOOL, self.OnStatusBarTube, id=1)
        self.Bind(wx.EVT_TOOL, self.OnStatusBarCylinder, id=2)
        self.Bind(wx.EVT_TOOL, self.OnStatusBarJunction, id=3)
        self.Bind(wx.EVT_TOOL, self.OnStatusBarTank, id=4)
        self.Bind(wx.EVT_TOOL, self.OnStatusBarAtmosphere, id=5)
        self.Bind(wx.EVT_TOOL, self.OnStatusBarValve, id=6)
        self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)
        self.Bind(wx.EVT_KEY_UP, self.OnKeyUp)
        self.Bind(wx.EVT_CHAR, self.OnChar)

        self.Bind(wx.EVT_TREE_ITEM_EXPANDED, self.OnItemExpanded, self.tree)
        self.Bind(wx.EVT_TREE_ITEM_COLLAPSED, self.OnItemCollapsed, self.tree)
        self.Bind(wx.EVT_TREE_SEL_CHANGED, self.OnSelChanged, self.tree)
        #self.Bind(wx.EVT_TREE_BEGIN_LABEL_EDIT, self.OnBeginEdit, self.tree)
        #self.Bind(wx.EVT_TREE_END_LABEL_EDIT, self.OnEndEdit, self.tree)
        self.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.OnActivate, self.tree)

        self.tree.Bind(wx.EVT_LEFT_DCLICK, self.OnLeftDClick)
        self.tree.Bind(wx.EVT_RIGHT_DOWN, self.OnRightDown)
        self.tree.Bind(wx.EVT_RIGHT_UP, self.OnRightUp)

        x = [(wx.ACCEL_NORMAL, wx.WXK_F1, self.UserHelp.GetId())]
        atable = wx.AcceleratorTable(x)
        self.SetAcceleratorTable(atable)

    def __set_properties(self):
        # begin wxGlade: Home.__set_properties
        self.SetTitle("ICESym-GUI")
        self.SetSize(wx.DLG_UNIT(self, wx.Size(314, 314)))
        self.SetFont(wx.Font(8, wx.DEFAULT, wx.NORMAL, wx.NORMAL, 0, "Sans"))
        self.home_statusbar.SetStatusWidths([-1])
        # statusbar fields
        home_statusbar_fields = ["status bar"]
        for i in range(len(home_statusbar_fields)):
            self.home_statusbar.SetStatusText(home_statusbar_fields[i], i)
        self.home_toolbar.Realize()
        self.window_1_pane_1.SetScrollRate(10, 10)
        ogl.OGLInitialize()
        self.canvas.SetBackgroundColour("WHITE")
        self.diagram = ogl.Diagram()
        self.canvas.SetDiagram( self.diagram )
        self.diagram.SetCanvas( self.canvas )
        self.window_1_pane_2.SetScrollRate(10, 10)
        self.window_1.SetMinSize(wx.DLG_UNIT(self.window_1, wx.Size(408, 200)))
        # end wxGlade

    def __do_layout(self):
        # begin wxGlade: Home.__do_layout
        sizer_1 = wx.BoxSizer(wx.HORIZONTAL)
        sizer_2 = wx.BoxSizer(wx.HORIZONTAL)
        sizer_3 = wx.BoxSizer(wx.HORIZONTAL)
        sizer_3.Add(self.tree, 1, wx.EXPAND, 0)	
        self.window_1_pane_1.SetSizer(sizer_3)
        sizer_2.Add(self.canvas, 1, wx.EXPAND, 0)
        self.window_1_pane_2.SetSizer(sizer_2)
        self.window_1.SplitVertically(self.window_1_pane_1, self.window_1_pane_2, 111)
        sizer_1.Add(self.window_1, 1, wx.EXPAND, 0)
        self.SetSizer(sizer_1)
        sizer_1.SetSizeHints(self)
        self.Layout()
        # end wxGlade

       
    def OnMenuFileOpen(self, event): # wxGlade: Home.<event_handler>
        if self.thisFile != 'untitled.py':
            self.closeFile()

        dlg = wx.FileDialog(self, message="Open a File", defaultDir="./saves",defaultFile="", wildcard="*.py", style=wx.FD_OPEN)
        if dlg.ShowModal() == wx.ID_OK:
            namefile = dlg.GetPath()
            self.readFile(namefile)
            self.SetTitle("ICESym-GUI: "+namefile)
        dlg.Destroy()


    def OnMenuFileSave(self, event): # wxGlade: Home.<event_handler>
        if self.Simulator == []:
            wx.MessageBox("You must Configure this Simulation Before", "Error")
        else:
            if self.thisFile == "untitled.py":
                dlg = wx.FileDialog(self, message="Save File", defaultDir="./saves", wildcard="*.py", style=wx.FD_SAVE)
                if dlg.ShowModal() == wx.ID_OK:
                    namefile = dlg.GetPath()
                    self.saveFile(namefile)
                dlg.Destroy()
            else:
                self.saveFile(self.thisFile)

    def OnMenuFileSaveAs(self, event): # wxGlade: Home.<event_handler>
        if self.Simulator == []:
            wx.MessageBox("You must Configure this Simulation Before", "Error")
        else:
            dlg = wx.FileDialog(self, message="Save File As", defaultDir="./saves", wildcard="*.py", style=wx.FD_SAVE|wx.FD_OVERWRITE_PROMPT)
            if dlg.ShowModal() == wx.ID_OK:
                namefile = dlg.GetPath()
                self.saveFile(namefile)
                self.thisFile = namefile
                self.SetTitle("ICESym-GUI: "+namefile)
                self.saved = 1
            dlg.Destroy()

    def OnMenuFileExit(self, event): # wxGlade: Home.<event_handler>
        if self.saved == 1:
            self.Close()
        else:
            md = wx.MessageDialog(None, 'Save changes in ' + self.thisFile + ' ?','Confirm', wx.YES_NO| wx.CANCEL | wx.ICON_QUESTION)
            res = md.ShowModal()
            if res == 5104: #NO
                self.Close()
            if res == 5103: #YES
                self.OnMenuFileSave("")
                self.Close()
            #if res == 5104: #CANCEL retorna al Simulador

    def OnMenuFileClose(self, event): # wxGlade: Home.<event_handler>
        if not(self.saved == 1):
            md = wx.MessageDialog(None, 'Save changes in ' + self.thisFile + ' ?','Confirm', wx.YES_NO| wx.CANCEL | wx.ICON_QUESTION)
            res = md.ShowModal()
            if res == 5103: #YES
                self.OnMenuFileSave("")
            if res == 5101: 
                return
        self.closeFile()

    def closeFile(self):
        couplingCode(self)
        self.parseData()
        self.SetTitle("ICESym-GUI")
        self.Simulator = []
        self.Cylinders = []
        self.Tanks = []
        self.Junctions = []
        self.Tubes = []
        self.Valves = []
        self.Atmospheres = []
        self.shapes = []
        self.connectionLines = []
        self.stateFromFile = 0
        self.thisFile = 'untitled.py'
        self.copyboard = ''
        self.canvas.GetDiagram().DeleteAllShapes()
        self.canvas.Refresh()	
        for e in self.itemsTree:
            for i in self.itemsTree[e]:
                self.tree.Delete(self.itemsTree[e][i])
            self.itemsTree[e] = {}
        # self.itemsTree = dict()

    def OnMenuEditCopy(self, event): # wxGlade: Home.<event_handler>
        (shapeObject,index) = self.findSelected()
        if shapeObject==-1 and index == -1:
            return
        if isinstance(shapeObject,ogl.BitmapShape):
            (element,indexElem) = self.shapes[index]
            #print element,indexElem
            if element == "Cylinders":
                self.copyboard = ("Cylinders", self.Cylinders[indexElem].copy())
            if element == "Valves":
                self.copyboard = ("Valves", self.Valves[indexElem].copy())
            if element == "Tubes":
                self.copyboard = ("Tubes", self.Tubes[indexElem].copy())
            if element == "Junctions":
                self.copyboard = ("Junctions", self.Junctions[indexElem].copy())
            if element == "Atmospheres":
                self.copyboard = ("Atmospheres", self.Atmospheres[indexElem].copy())
            if element == "Tanks":
                self.copyboard = ("Tanks", self.Tanks[indexElem].copy())
            self.copynumber = 0

    def OnMenuEditPaste(self, event): # wxGlade: Home.<event_handler>
        if not(self.copyboard == ''):
            element = self.copyboard[0]
            if element == "Cylinders":
                cyl = self.copyboard[1].copy()
                index = len(self.Cylinders)
                self.Cylinders.append(cyl)
                self.Cylinders[-1]['label'] = self.Cylinders[-1]['label'] + "_copy" + str(self.copynumber)
                self.addShape(element,index)
            if element == "Valves":
                valve = self.copyboard[1].copy()
                index = len(self.Valves)
                self.Valves.append(valve)
                self.Valves[-1]['label'] = self.Valves[-1]['label'] + "_copy" + str(self.copynumber)
                self.addShape(element,index)
            if element == "Tubes":
                tube = self.copyboard[1].copy()
                index = len(self.Tubes)
                self.Tubes.append(tube)
                self.Tubes[-1]['label'] = self.Tubes[-1]['label'] + "_copy" + str(self.copynumber)
                self.addShape(element,index)
            if element == "Junctions":
                junc = self.copyboard[1].copy()
                index = len(self.Junctions)
                self.Junctions.append(junc)
                self.Junctions[-1]['label'] = self.Junctions[-1]['label'] + "_copy" + str(self.copynumber)
                self.addShape(element,index)
            if element == "Atmospheres":
                atm = self.copyboard[1].copy()
                index = len(self.Atmospheres)
                self.Atmospheres.append(atm)
                self.addShape(element,index)
            if element == "Tanks":
                tank = self.copyboard[1].copy()
                index = len(self.Tanks)
                self.Tanks.append(tank)
                self.Tanks[-1]['label'] = self.Tanks[-1]['label'] + "_copy" + str(self.copynumber)
                self.addShape(element,index)
            self.copynumber = self.copynumber + 1

    def OnMenuEditDelete(self, event):
        (shapeObject,index) = self.findSelected()
        if shapeObject==-1 and index == -1:
            return
            
        if isinstance(shapeObject,ogl.BitmapShape):
            if self.canDeleteShape(index)==1:
                md = wx.MessageDialog(None, 'Are you Sure to delete this Element?','Confirm', wx.YES_NO | wx.ICON_QUESTION)
                res = md.ShowModal()
                if res == 5103:
                    self.deleteShape(index, shapeObject)
            else:
                wx.MessageBox("You can't delete this element because it has Connections", "Error")
        else:
            if self.canDeleteLine(index)==1:
                md = wx.MessageDialog(None, 'Are you Sure to delete this Connection?','Confirm', wx.YES_NO | wx.ICON_QUESTION)
                res = md.ShowModal()
                if res == 5103:
                    self.deleteLine(index, shapeObject)
            else:
                wx.MessageBox("You can't delete this connection, first you must delete valve-tube connection", "Error")

    def OnMenuSimulationConfigure(self, event): # wxGlade: Home.<event_handler>
        simulation = formSimulation(None, -1, "")
        if(self.Simulator==[]):
            self.loadGeneric(simulation.data,'simulation','default',['calc_engine_data'],['rpms','ig_order'])  
        else:
            self.loadGeneric(simulation.data,'simulation',0,['calc_engine_data'],['rpms','ig_order'])
        ret = simulation.ShowModal()
        if ret==5100:
            Sim = self.upGeneric(simulation.data,'simulation',['filesave_state','filesave_spd','filein_state','folder_name'],['ncycles','nsave','nstroke','calc_engine_data'],['rpms','ig_order'])
            if simulation.data['get_state'].GetSelection()==1 or simulation.data['get_state'].GetSelection()==2:
                self.stateFromFile = 1

            if simulation.data['calc_engine_data'].GetValue()==1:
                for i in range(len(self.Cylinders)):
                    self.Cylinders[i]['ownState'] = 1
                    self.Cylinders[i]['extras'] = 1
                default_values.dict_cylinder['ownState'] = bool(1)
                default_values.dict_cylinder['extras'] = bool(1)
                self.calcEngine = 1
            else:
                default_values.dict_cylinder['ownState'] = bool(0)
                default_values.dict_cylinder['extras'] = bool(0)
                self.calcEngine = 0
 
            if self.Simulator == []:
                self.Simulator.append(Sim)
            else:
                self.Simulator[0] = Sim

    def OnMenuSimulationRun(self, event): # wxGlade: Home.<event_handler>
        d = self.hasDisconnections()
        if len(d) > 0:
            sd = List2String(d)
            md = wx.MessageDialog(None, 'This Elements are disconnected: ' + sd,'WARNING!!', wx.ICON_EXCLAMATION)
            md.ShowModal()
        else:
            if not(self.saved):
                self.OnMenuFileSave('')

            filename = self.thisFile
            
            import sys
            i1 = filename.rfind("/")
            pathName = ''
            for j in range(i1):
                pathName = pathName + filename[j]
            i2 = filename.rfind(".")
            moduleName = ''
            for j in range(i2-i1-1):
                moduleName = moduleName + filename[j+i1+1]

            archi = open(self.pathCode + "exec.py", "w")

            pathName = pathName.encode("utf-8")
            moduleName = moduleName.encode("utf-8")

            lines = ['# coding= utf-8\n',
                'from numpy import array\n',
                'import time\n',
                'import sys\n',
                'import os\n',
                'from simCythonCPP import Simulator\n\n',
                'sys.path.append("'+ pathName + '")\n',
                'data = __import__("' + moduleName + '")\n',
                'now = time.time()\n',
                'Sim = Simulator(**data.kargs)\n',
                'print "termina de inicializar"\n',
                'Sim.printData()\n',
                'Sim.solver()\n',
                'now2 = time.time()\n',
                'print now2-now\n']
            
            archi.writelines([str(x) for x in lines])

            archi.close()

            os.system("python2.7 "+self.pathCode+"exec.py &")

    def OnMenuSimulationPost(self, event): # wxGlade: Home.<event_handler>
        folder_name = self.pathTests + "tests/" + self.Simulator[0]['folder_name']
        if self.Simulator == []:
            wx.MessageBox("This Simulation Haven't Results yet!!", "Error")
        else:
            post = PostProcess(None,-1,"")
            if(post.loadResults(folder_name)):
               post.Show()
            else:
                wx.MessageBox("This Simulation Haven't Results yet", "Error")

    def OnMenuHelpAbout(self, event): # wxGlade: Home.<event_handler>
        dlg = About(self)
        dlg.ShowModal()
        dlg.Destroy()

    def OnMenuUserHelp(self, event): # wxGlade: Home.<event_handler>
        help = Help(None, -1, "")
        help.Show()


    def OnStatusBarValve(self, event, edit=-1): # wxGlade: Home.<event_handler>
        valve = formValve(None, -1, "")
        if edit==-1:
            self.loadGeneric(valve.data,'valve','default',['histo'])
        else:
            self.loadGeneric(valve.data,'valve',edit,['histo'])
            valve.edit = edit
            if self.Valves[valve.edit]['type_dat']==2:
                valve.data['Lvmax'].Enable(False)
                valve.data['Lv'].Enable(True)

        valve.setLabels()
        ret = valve.ShowModal()
        if(ret==5100):
            Valve = self.upGeneric(valve.data,'valve',['label'],['Nval', 'histo'])
            if valve.edit == -1:
                index = len(self.Valves)
                Valve['edit'] = index
                self.Valves.append(Valve)
                self.addShape('Valves', index)
            else:
                Valve['position'] = self.Valves[valve.edit]['position']
                Valve['tube'] = self.Valves[valve.edit]['tube']
                Valve['ncyl'] = self.Valves[valve.edit]['ncyl']
                Valve['typeVal'] = self.Valves[valve.edit]['typeVal']
                self.Valves[valve.edit] = Valve
            self.saved = 0

    def OnStatusBarCylinder(self, event, edit=-1): # wxGlade: Home.<event_handler>
        cylinder = formCylinder(None, -1, "")

        if edit==-1:
            self.loadGeneric(cylinder.data,'cylinder','default',['scavenge','full_implicit','ownState','extras'],['histo'])
            self.loadGeneric(cylinder.combustion,'combustion','default',[])
            self.loadGeneric(cylinder.fuel,'fuel','default')
            self.loadGeneric(cylinder.injection,'injection','default')
        else:
            self.loadGeneric(cylinder.data,'cylinder',edit,['scavenge','full_implicit','ownState','extras'],['histo'])
            if cylinder.data['scavenge'].GetValue()==1:
                cylinder.data['scavenge_type'].Enable(True)
            self.loadGeneric(cylinder.combustion,'combustion',edit,[])
            self.loadGeneric(cylinder.fuel,'fuel',edit)
            self.loadGeneric(cylinder.injection,'injection',edit)
            cylinder.edit = edit
            if cylinder.combustion['combustion_model'].GetSelection()==0:
                cylinder.combustion['xbdot_array'].Enable(True)
            if cylinder.data['type_ig'].GetSelection()==1:
                for key in cylinder.injection:
                    cylinder.injection[key].Enable(True)
                if cylinder.injection['pulse'].GetSelection()!=2:
                    cylinder.injection['mfdot_array'].Enable(False)
                if cylinder.injection['ignition_delay_model'].GetSelection()!=2:
                    cylinder.injection['theta_id'].Enable(False)
                cylinder.combustion['combustion_model'].EnableItem(2, True)
                cylinder.combustion['combustion_model'].EnableItem(3, True)

        cylinder.onChangeNodes("")
        cylinder.setLabels()
        ret = cylinder.ShowModal()
        if(ret==5100):
            Cyl               = self.upGeneric(cylinder.data,'cylinder',['label'],['nnod','ndof','ownState','extras'],['histo'])
            Cyl['fuel']       = self.upGeneric(cylinder.fuel,'fuel',[])
            Cyl['combustion'] = self.upGeneric(cylinder.combustion,'combustion',[])
            Cyl['injection']  = self.upGeneric(cylinder.injection,'injection',[])
            if cylinder.edit == -1:
                index =  len(self.Cylinders)
                Cyl['edit'] = index
                self.Cylinders.append(Cyl)
                self.addShape('Cylinders',index)
            else:
                Cyl['position'] = self.Cylinders[cylinder.edit]['position']
                self.Cylinders[cylinder.edit] = Cyl
            self.saved = 0
        cylinder.Destroy()

    def OnStatusBarJunction(self, event, edit=-1): # wxGlade: Home.<event_handler>
        junction = formJunction(None, -1, "")
        
        if edit == -1:
            self.loadGeneric(junction.data,'junction','default',['extras'],[],['histo'])
            junction.addHisto()
        else:
            self.loadGeneric(junction.data,'junction',edit,['extras'],[],['histo'])
            labels = self.findTubesNames(self.Junctions[edit]['node2tube'])
            junction.addHisto(labels)
            self.setHisto(self.Junctions[edit]['histo'],junction.data['histo'])
            junction.edit = edit

        ret = junction.ShowModal()
        if ret==5100:
            Junc = self.upGeneric(junction.data,'junction',['label'],['ndof','nnod','extras'],[],['histo'])
            if junction.edit == -1:
                index =  len(self.Junctions)
                Junc['edit'] = index
                self.Junctions.append(Junc)
                self.addShape('Junctions',index) 
            else:
                Junc['position'] = self.Junctions[junction.edit]['position']
                Junc['type_end'] = self.Junctions[junction.edit]['type_end']
                Junc['node2tube'] = self.Junctions[junction.edit]['node2tube']
                self.Junctions[junction.edit] = Junc
            self.saved = 0
            
    def OnStatusBarAtmosphere(self, event, edit=-1): # wxGlade: Home.<event_handler>
        atm = formAtmosphere(None, -1, "")
        
        if edit==-1:
            self.loadGeneric(atm.data,'atmosphere','default')
        else:
            self.loadGeneric(atm.data,'atmosphere',edit)
            atm.edit = edit
        
        ret = atm.ShowModal()
        if ret==5100:
            Atm = dict()
            Atm['state_ini'] = []
            Atm['state_ini'].append(float(atm.data['rho'].GetValue()))
            Atm['state_ini'].append(float(atm.data['u'].GetValue()))
            Atm['state_ini'].append(float(atm.data['p'].GetValue()))
            if atm.edit == -1:
                index = len(self.Atmospheres)
                Atm['edit'] = index
                self.Atmospheres.append(Atm)
                self.addShape('Atmospheres',index) 
            else:
                Atm['position'] = self.Atmospheres[atm.edit]['position']
                self.Atmospheres[atm.edit] = Atm
            self.saved = 0
     
    def OnStatusBarTube(self, event, edit=-1): # wxGlade: Home.<event_handler>
        tube = formTube(None, -1, "")
 
        if edit==-1: 
            self.loadGeneric(tube.data,'tube','default',[],['histo'])
        else:
            self.loadGeneric(tube.data,'tube',edit,[],['histo'])
            tube.edit = edit
 
        tube.onHistoMode("")
        tube.setLabels()
        ret = tube.ShowModal()
        
        if(ret==5100):
            Tube = self.upGeneric(tube.data,'tube',['label'],['nnod','ndof','numNorm'],['histo'])
            Tube['histo'] = tube.calculateHisto()
            if tube.edit == -1:
                index = len(self.Tubes)
                Tube['edit'] = index
                self.Tubes.append(Tube)
                self.addShape('Tubes',index) 
            else:
                Tube['position'] = self.Tubes[tube.edit]['position']
                Tube['nright'] = self.Tubes[tube.edit]['nright'] 
                Tube['tright'] = self.Tubes[tube.edit]['tright'] 
                Tube['nleft'] = self.Tubes[tube.edit]['nleft'] 
                Tube['tleft'] = self.Tubes[tube.edit]['tleft'] 
                self.Tubes[tube.edit] = Tube
            self.saved = 0

    def OnStatusBarTank(self, event, edit=-1): # wxGlade: Home.<event_handler>
        tank = formTank(None, -1, "")

        if edit==-1:
            self.loadGeneric(tank.data,'tank','default',['extras'],[],['histo'])
            tank.addHisto()
        else:
            self.loadGeneric(tank.data,'tank',edit,['extras'],[],['histo'])
            labels = self.findTubesNames(self.Tanks[edit]['int2tube'] + self.Tanks[edit]['exh2tube'])
            tank.addHisto(labels)
            self.setHisto(self.Tanks[edit]['histo'],tank.data['histo'])
            tank.edit = edit
        
        tank.onChangeNnod("")
        tank.setLabels()
        ret = tank.ShowModal()
        
        if(ret==5100):
            Tank = self.upGeneric(tank.data,'tank',['label'],['nnod','ndof','extras'],[],['histo'])
            if tank.edit == -1:
                index =  len(self.Tanks)
                Tank['edit'] = index
                self.Tanks.append(Tank)
                self.addShape('Tanks',index)
            else:
                Tank['position'] = self.Tanks[tank.edit]['position']
                Tank['int2tube'] = self.Tanks[tank.edit]['int2tube']
                Tank['exh2tube'] = self.Tanks[tank.edit]['exh2tube']
                self.Tanks[tank.edit] = Tank
            self.saved = 0

    def loadGeneric(self,generic,tipo,edit,listCheck=[],listList=[],listCheckList=[]):
        #generic: instancia del objeto formulario
        #tipo: tipo de componente
        if tipo=='simulation':
             dict_generic = default_values.dict_simulation
             if not(edit=="default"):
                 Generic = self.Simulator[edit]
        if tipo=='cylinder':
             dict_generic = default_values.dict_cylinder
             if not(edit=="default"):
                 Generic = self.Cylinders[edit]  
             if self.stateFromFile == 1:
                 generic['state_ini'].Enable(1)
             if self.calcEngine == 1:
                 generic['ownState'].Enable(1)
                 generic['extras'].Enable(1)
        if tipo=='junction':
             dict_generic = default_values.dict_junction
             if not(edit=="default"):
                 Generic = self.Junctions[edit]  
        if tipo=='tube':
             dict_generic = default_values.dict_tube
             if not(edit=="default"):
                 Generic = self.Tubes[edit]  
             if self.stateFromFile == 1:
                 generic['state_ini'].Enable(1)
        if tipo=='tank':
             dict_generic = default_values.dict_tank
             if not(edit=="default"):
                 Generic = self.Tanks[edit] 
             if self.stateFromFile == 1:
                 generic['state_ini'].Enable(1) 
        if tipo=='valve':
             dict_generic = default_values.dict_valve
             if not(edit=="default"):
                 Generic = self.Valves[edit]
             #if self.stateFromFile == 1:
             #    generic[10].Enable(0)  
        if tipo=='atmosphere':
             dict_generic = default_values.dict_atmosphere
             if not(edit=="default"):
                 Generic = dict()
                 Generic['rho'] = self.Atmospheres[edit]['state_ini'][0]
                 Generic['u'] = self.Atmospheres[edit]['state_ini'][1] 
                 Generic['p'] = self.Atmospheres[edit]['state_ini'][2]  
        if tipo=='combustion':
             dict_generic = default_values.dict_combustion
             if not(edit=="default"):
                 Generic = self.Cylinders[edit]['combustion']
        if tipo=='injection':
             dict_generic = default_values.dict_injection
             if not(edit=="default"):
                 Generic = self.Cylinders[edit]['injection']
        if tipo=='fuel':
             dict_generic = default_values.dict_fuel
             if not(edit=="default"):
                 Generic = self.Cylinders[edit]['fuel']
        if(edit=='default'):
            for key in dict_generic:
                #print "key: ", key 
                if isinstance(generic[key],wx.grid.Grid):
                    setGrid(dict_generic[key],generic[key])	
                else:
                    if isinstance(generic[key],wx.RadioBox):
                         generic[key].SetSelection(dict_generic[key])
                    elif key in listCheck:
                        generic[key].SetValue(dict_generic[key])
                    elif key in listList:
                        generic[key].SetValue(List2String(dict_generic[key]))
                    elif key not in listCheckList:
                        generic[key].SetValue(str(dict_generic[key]))
        else:
            for key in dict_generic:
                if key in Generic.keys() and not(Generic[key]=="<none>"):
                    # print names_generic[i],": ",Generic[names_generic[i]]
                    if isinstance(generic[key],wx.grid.Grid):
                        setGrid(Generic[key],generic[key])	
                    else:
                        if isinstance(generic[key],wx.RadioBox):
                            generic[key].SetSelection(Generic[key])
                        elif key in listCheck:
                            generic[key].SetValue(Generic[key]) 
                        elif key in listList:
                            generic[key].SetValue(List2String(Generic[key])) 
                        elif key not in listCheckList:
                            generic[key].SetValue(str(Generic[key]))
                else:
                    generic[key].Enable(0)
        if tipo=='cylinder' and self.calcEngine == 0: #malo, pero me salva aca
            generic['ownState'].Enable(1)
            generic['extras'].Enable(1)		

    def upGeneric(self,generic,tipo,listStr=[],listInt=[], listList=[], listCheckList=[]):
        if tipo=='simulation':
            dict_generic = default_values.dict_simulation
        if tipo=='cylinder':
            dict_generic = default_values.dict_cylinder
        if tipo=='junction':
            dict_generic = default_values.dict_junction
        if tipo=='tube':
            dict_generic = default_values.dict_tube
        if tipo=='tank':
            dict_generic = default_values.dict_tank
        if tipo=='valve':
            dict_generic = default_values.dict_valve
        if tipo=='atmosphere':
            dict_generic = default_values.dict_atmosphere
        if tipo=='combustion':
            dict_generic = default_values.dict_combustion
        if tipo=='injection':
            dict_generic = default_values.dict_injection
        if tipo=='fuel':
            dict_generic = default_values.dict_fuel

        Gen = dict()
        for key in generic:
            if(generic[key].IsEnabled()):
                if isinstance(generic[key],wx.grid.Grid):
                    Gen[key] = upGrid(generic[key])
                else:
                    if isinstance(generic[key],wx.RadioBox):
                        Gen[key] = generic[key].GetSelection()
                    else:
                        if key in listInt:
                            Gen[key] = int(generic[key].GetValue())
                        elif key in listStr:
                            Gen[key] = generic[key].GetValue()   
                        elif key in listList:
                            lista = generic[key].GetValue()
                            Gen[key] = String2List(lista)
                        elif key in listCheckList:
                            Gen[key] = []
                            for j in range(generic[key].GetCount()):
                                if generic[key].IsChecked(j):
                                    Gen[key].append(j)
                        else:
                            Gen[key] = float(generic[key].GetValue())
            else:
                Gen[key] = "<none>"    
        return Gen

    def setHisto(self,dataHisto,objectHisto):
        for i in range(len(dataHisto)):
            objectHisto.Check(dataHisto[i],True)

    #def onExportPythonScript(self, event): # wxGlade: Home.<event_handler>
    #    print "Event handler `onExportPythonScript' not implemented"
    #    event.Skip()

    def readFile(self,filename):
        archi = open(filename, "r")
        line = archi.readline()
        if line=="#### ---- ####\n":
            import sys
            pathName = os.path.dirname(filename)
            sys.path.append(pathName)
            moduleName = os.path.basename(filename)
            moduleName = os.path.splitext(moduleName)[0]
            #print "DEBUG: ", moduleName, pathName
            externalData = __import__(moduleName)

            self.Simulator.append(externalData.Simulator)
            self.Cylinders = externalData.Cylinders
            self.Tanks = externalData.Tanks
            self.Junctions = externalData.Junctions
            self.Tubes = externalData.Tubes
            self.Valves = externalData.Valves
            self.Atmospheres = externalData.Atmospheres
            #self.shapes = externalData.shapes 
            decouplingCode(self)
            self.completeData()
            self.redrawConnections()  
      
            self.thisFile = filename     
            print "Leido: ",filename
            self.saved = 1
            #self.redibujar()
        else:
             wx.MessageBox("The selected file has not the requeried format, please select another", "Error")

    def saveFile(self,filename):
        couplingCode(self)
        archi = open(filename, "w")
        lines = ["#### ---- ####\n", "# Archivo generado por SimulatorGUI\n", "# CIMEC - Santa Fe - Argentina \n", "# Adecuado para levantar desde Interfaz Grafica \n", "# O para correr desde consola mediante $python main.py \n","#### ---- ####\n\n"]
        archi.writelines(lines)
        self.parseData()
        lines = getWriteList('Simulator', self.Simulator, default_values.dict_simulation)       
        archi.writelines(lines)
        lines = getWriteList('Cylinders', self.Cylinders, default_values.dict_cylinder)       
        archi.writelines(lines)
        lines = getWriteList('Valves', self.Valves, default_values.dict_valve)       
        archi.writelines(lines)                                                                  
        lines = getWriteList('Tubes', self.Tubes, default_values.dict_tube)       
        archi.writelines(lines)    
        lines = getWriteList('Tanks', self.Tanks, default_values.dict_tank)       
        archi.writelines(lines)    
        lines = getWriteList('Junctions', self.Junctions, default_values.dict_junction)       
        archi.writelines(lines)    
        lines = getWriteList('Atmospheres', self.Atmospheres, default_values.dict_atmosphere)       
        archi.writelines(lines)    
        lines = ["\n\nkargs = {'Simulator':Simulator, 'Cylinders':Cylinders, 'Junctions':Junctions, 'Tubes':Tubes, 'Tanks':Tanks, 'Atmospheres':Atmospheres}\n"]
        archi.writelines(lines)
        archi.close()
        print "Guardado: ",filename
        self.saved = 1
        self.deparseData()
        decouplingCode(self)


    # sirve en el caso de que no se hayan guardado datos por disabled, 
    # para que si se levantan y se quiere guardar (sin acceder al form) los guarde correctamente
    # realiza el "deparseData()", operacion ontraria a lo que hace "parseData()"
    # ademas carga el diagrama
    def completeData(self):
        self.canvas.GetDiagram().DeleteAllShapes()
        self.shapes = []
        self.deparseData()

    def deparseData(self):
        rad2deg = 180.0 / 3.14159265358979
        m2mm = 1000.0
        sqm2sqcm = 10000.0
        cm2ccm = 1000000.0
        for i in range(len(self.Simulator)):
            self.completeObject(self.Simulator[i],default_values.dict_simulation)
            self.Simulator[i]['nstroke'] = self.Simulator[i]['nstroke']/2 - 1
            for j in range(len(self.Cylinders)):
                self.Simulator[i]['ig_order'][j] += 1

        for i in range(len(self.Cylinders)):
            # Geometric data
            Vd = 0.5*3.14159265358979*self.Cylinders[i]['Bore']**2*self.Cylinders[i]['crank_radius']
            Vc = self.Cylinders[i]['Vol_clearance']
            self.Cylinders[i]['Bore'] *= m2mm
            self.Cylinders[i]['crank_radius'] *= 2*m2mm # data is crank radious
            self.Cylinders[i]['rod_length'] *= m2mm
            self.Cylinders[i]['head_chamber_area'] *= sqm2sqcm
            self.Cylinders[i]['piston_area'] *= sqm2sqcm
            self.Cylinders[i]['delta_ca'] *= rad2deg
            self.Cylinders[i]['Vol_clearance'] = Vd/Vc+1
            # Heat transfer data
            self.Cylinders[i]['model_ht'] -= 1

            self.completeObject(self.Cylinders[i],default_values.dict_cylinder)
            self.completeObject(self.Cylinders[i]['fuel'],default_values.dict_fuel)
            # Fuel data
            self.Cylinders[i]['fuel']['Q_fuel'] *= 1e-6
            self.Cylinders[i]['fuel']['hvap_fuel'] *= 1e-3
            # Combustion data
            self.Cylinders[i]['combustion']['theta_ig_0'] *= rad2deg
            self.Cylinders[i]['combustion']['dtheta_comb'] *= rad2deg
            self.completeObject(self.Cylinders[i]['combustion'],default_values.dict_combustion)
            # Injection data
            if self.Cylinders[i]['type_ig']==1:
                self.Cylinders[i]['injection']['m_inj'] *= 1e3
                self.Cylinders[i]['injection']['theta_inj_ini'] *= rad2deg
                self.Cylinders[i]['injection']['dtheta_inj'] *= rad2deg
                if self.Cylinders[i]['injection']['ignition_delay_model']==2:
                    self.Cylinders[i]['injection']['theta_id'] *= rad2deg
            self.completeObject(self.Cylinders[i]['injection'],default_values.dict_injection)
            if "pulse" in self.Cylinders[i]['injection'].keys() and not(self.Cylinders[i]['injection']['pulse']=="<none>"):
                self.Cylinders[i]['injection']['pulse'] -= 1
            self.addShape("Cylinders",i,self.Cylinders[i]['position'][0],self.Cylinders[i]['position'][1],1)

        for i in range(len(self.Junctions)):
            self.Junctions[i]['modelo_junc'] -= 1
            self.completeObject(self.Junctions[i],default_values.dict_junction)
            self.addShape("Junctions",i,self.Junctions[i]['position'][0],self.Junctions[i]['position'][1],1)
   
        for i in range(len(self.Tubes)):
            self.Tubes[i]['longitud'] *= m2mm
            for j in range(len(self.Tubes[i]['xnod'])):
                self.Tubes[i]['xnod'][j] *= m2mm
                self.Tubes[i]['diameter'][j] *= m2mm
            self.completeObject(self.Tubes[i],default_values.dict_tube)
            self.addShape("Tubes",i,self.Tubes[i]['position'][0],self.Tubes[i]['position'][1],1)

        for i in range(len(self.Tanks)):
            self.completeObject(self.Tanks[i],default_values.dict_tank)
            self.addShape("Tanks",i,self.Tanks[i]['position'][0],self.Tanks[i]['position'][1],1)
            self.Tanks[i]['Volume'] *= cm2ccm
            self.Tanks[i]['mass'] *= 1e3
            self.Tanks[i]['Area_wall'] *= sqm2sqcm

        for i in range(len(self.Atmospheres)):
        #    self.completeObject(self.Atmospheres[i]['state_ini'],default_values.dict_atmosphere)
            self.addShape("Atmospheres",i,self.Atmospheres[i]['position'][0],self.Atmospheres[i]['position'][1],1)

        for i in range(len(self.Valves)):
            self.Valves[i]['type_dat'] += 1
            self.Valves[i]['angle_V0'] *= rad2deg
            self.Valves[i]['angle_VC'] *= rad2deg
            self.Valves[i]['Dv'] *= m2mm
            if self.Valves[i]['type_dat'] != 2:
                self.Valves[i]['Lvmax'] *= m2mm
            for j in range(len(self.Valves[i]['Cd'])):
                self.Valves[i]['Cd'][j][0] *= m2mm
            if self.Valves[i]['type_dat']==2:
                for j in range(len(self.Valves[i]['Lv'])):
                    self.Valves[i]['Lv'][j][1] *= m2mm
            self.completeObject(self.Valves[i],default_values.dict_valve)
            self.addShape("Valves",i,self.Valves[i]['position'][0],self.Valves[i]['position'][1],1)

    def completeObject(self, objectData, dict_generic):
        for key in dict_generic:
             if not(key in objectData.keys()):
                 objectData[key] = '<none>'
        #print objectData		

# modifica algunos valores paa que sean compatibles con el simulador en c++
    def parseData(self):
        deg2rad = 3.14159265358979 / 180.0
        mm2m = 0.001
        sqcm2sqm = 0.0001
        ccm2cm = 0.000001
        if len(self.Simulator)>0:
            self.Simulator[0]['nstroke'] = self.Simulator[0]['nstroke']*2+2
            for j in range(len(self.Cylinders)):
                self.Simulator[0]['ig_order'][j] -= 1

        for i in range(len(self.Junctions)):
            self.Junctions[i]['modelo_junc'] += 1

        for i in range(len(self.Cylinders)):
            # Geometric data
            self.Cylinders[i]['Bore'] *= mm2m
            self.Cylinders[i]['crank_radius'] *= 0.5*mm2m # input is the stroke
            self.Cylinders[i]['rod_length'] *= mm2m
            self.Cylinders[i]['head_chamber_area'] *= sqcm2sqm
            self.Cylinders[i]['piston_area'] *= sqcm2sqm
            self.Cylinders[i]['delta_ca'] *= deg2rad
            Vd = 0.5*3.14159265358979*self.Cylinders[i]['Bore']**2*self.Cylinders[i]['crank_radius']
            Vc = Vd/(self.Cylinders[i]['Vol_clearance']-1)
            self.Cylinders[i]['Vol_clearance'] = Vc
            # Heat transfer data
            self.Cylinders[i]['model_ht'] += 1
            # Fuel data
            self.Cylinders[i]['fuel']['Q_fuel'] *= 1e6
            self.Cylinders[i]['fuel']['hvap_fuel'] *= 1e3
            # Combustion data
            self.Cylinders[i]['combustion']['theta_ig_0'] *= deg2rad
            self.Cylinders[i]['combustion']['dtheta_comb'] *= deg2rad
            # Injection data
            if self.Cylinders[i]['type_ig']==1:
                self.Cylinders[i]['injection']['m_inj'] *= 1e-3
                self.Cylinders[i]['injection']['theta_inj_ini'] *= deg2rad
                self.Cylinders[i]['injection']['dtheta_inj'] *= deg2rad
                if self.Cylinders[i]['injection']['ignition_delay_model']==2:
                    self.Cylinders[i]['injection']['theta_id'] *= deg2rad
            if "pulse" in self.Cylinders[i]['injection'].keys() and not(self.Cylinders[i]['injection']['pulse']=="<none>"):
                self.Cylinders[i]['injection']['pulse'] += 1

        for i in range(len(self.Valves)):
            self.Valves[i]['type_dat'] -= 1
            self.Valves[i]['angle_V0'] *= deg2rad
            self.Valves[i]['angle_VC'] *= deg2rad
            self.Valves[i]['Dv'] *= mm2m
            if self.Valves[i]['type_dat'] != 1:
                self.Valves[i]['Lvmax'] *= mm2m #a metros
            for j in range(len(self.Valves[i]['Cd'])):
                self.Valves[i]['Cd'][j][0] *= mm2m
            if self.Valves[i]['type_dat']==1:
                for j in range(len(self.Valves[i]['Lv'])):
                    self.Valves[i]['Lv'][j][1] *= mm2m

        for i in range(len(self.Tubes)):
            self.Tubes[i]['longitud'] *= mm2m
            for j in range(len(self.Tubes[i]['xnod'])):
                self.Tubes[i]['xnod'][j] *= mm2m
                self.Tubes[i]['diameter'][j] *= mm2m

        for i in range(len(self.Tanks)):
            self.Tanks[i]['Volume'] *= ccm2cm
            self.Tanks[i]['mass'] *= 1e-3
            self.Tanks[i]['Area_wall'] *= sqcm2sqm

####--------------------------------------------####

# ---  BEGIN DIAGRAM CONTROL CODE -----#

####--------------------------------------------####

    def addShape(self,element,index,x=25,y=25, load=-1): 
        
        if not(element=="Valves"):
            name = 'images/'+ element +'IconeSmall.bmp'
        else:
            if self.Valves[index]['type']==0:
                name = 'images/'+ element +'IntakeIconeSmall.bmp' 
            else:
                name = 'images/'+ element +'ExhaustIconeSmall.bmp'  

        bmp = wx.Bitmap(name)
        mask = wx.Mask(bmp, wx.BLUE)
        bmp.SetMask(mask)
        shape = ogl.BitmapShape()
        shape.SetBitmap(bmp)
        shape.SetX(x)
        shape.SetY(y)
        
        evthandler = MyEvtHandler("","")
        evthandler.SetShape(shape)
        evthandler.SetPreviousHandler(shape.GetEventHandler())
        shape.SetEventHandler(evthandler)

        self.shapes.append((element,index))
        self.updatePosition(len(self.shapes)-1,x,y)
        if load==-1: #cuando cargamos de un archivo no se inician las conexiones
            self.initConnections(element,index)
        #print (element,index)
        label = self.getLabel(element,index)
        self.canvas.AddShape(shape)
        self.canvas.Refresh()
        self.addItemTree(element,index,label)
        self.diagram.ShowAll( 1 )


    def editGeneric(self, shapesIndex):
        element = self.shapes[shapesIndex][0]
        index = self.shapes[shapesIndex][1]
        if element == "Cylinders":
            self.OnStatusBarCylinder("",index)
        if element == "Junctions":
            self.OnStatusBarJunction("",index)
        if element == "Tubes":
            self.OnStatusBarTube("",index)
        if element == "Tanks":
            self.OnStatusBarTank("",index)
        if element == "Valves":
            self.OnStatusBarValve("",index)
        if element == "Atmospheres":
            self.OnStatusBarAtmosphere("",index)

    def updatePosition(self,shapesIndex,x,y):
        element = self.shapes[shapesIndex][0]
        index = self.shapes[shapesIndex][1]
        if element == "Cylinders":
            self.Cylinders[index]['position'] = (x,y)
        if element == "Junctions":
            self.Junctions[index]['position'] = (x,y)
        if element == "Tubes":
            self.Tubes[index]['position'] = (x,y)
        if element == "Tanks":
            self.Tanks[index]['position'] = (x,y)
        if element == "Valves":
            self.Valves[index]['position'] = (x,y)
        if element == "Atmospheres":
            self.Atmospheres[index]['position'] = (x,y)
        self.saved = 0

    #recibe del manejador de eventos los candidatos a conectarse
    def makeConection(self, shapeObjectFrom, shapeIndexFrom, shapeObjectTo, shapeIndexTo, test=-1):
        shapeFrom = self.shapes[shapeIndexFrom]
        shapeTo = self.shapes[shapeIndexTo]
        #print self.shapes
        #print shapeObjectFrom
        #print shapeObjectTo
        #print "ShapeFrom: ",shapeFrom[0]
        #print "ShapeTo: ",shapeTo[0]
        if(test==-1):                                 
            test = self.possibleConnection(shapeFrom, shapeTo)
        
        if test == 1:
            line = ogl.LineShape()
            line.SetCanvas(self.canvas)
            line.SetPen(wx.BLACK_PEN)
            line.SetBrush(wx.BLACK_BRUSH)
            line.AddArrow(ogl.ARROW_ARROW)
            line.MakeLineControlPoints(2)
            shapeObjectFrom.AddLine(line,shapeObjectTo)
            evthandler = MyLineEvtHandler("","")
            evthandler.SetShape(line)
            evthandler.SetPreviousHandler(line.GetEventHandler())
            line.SetEventHandler(evthandler)
            self.diagram.AddShape(line)
            line.Show(True)
            self.connectionLines.append((shapeIndexFrom,shapeIndexTo))
            self.saved = 0
        else:
            wx.MessageBox(test, "Error")      

     #dibuja las conexiones cuando se levantan los datos
    def redrawConnections(self):
         i = 0
         shapeList = self.canvas.GetDiagram().GetShapeList()
         for s in self.shapes:
             element = s[0]
             index   = s[1]
             #print "a conectar: ",element,index
             if element == "Tubes":
                 if not(self.Tubes[index]['nright'])==-1:
                     shapeObjectFrom = shapeList[i]
                     shapeIndexFrom = i
                     nameElement = ""
                     shapeObjectTo = ''
                     shapeIndexTo = ''

                     if self.Tubes[index]['tright'] in ["tank","tube","junction","atmosphere"]:
                         nameElement = default_values.name2element[self.Tubes[index]['tright']]   
                         (shapeObjectTo,shapeIndexTo) = self.findShape(nameElement,self.Tubes[index]['nright'])  
                     #else: si esta conectado a un cylinder
                     if self.Tubes[index]['tright'] == "cylinder": #si esta conectado a un cilindro, en realidad va a una valvula
                         nameElement = "Valves"
                         (shapeObjectTo,shapeIndexTo) = self.findShape(nameElement,index) #ahora le envio mi numero de tube

                     self.makeConection(shapeObjectFrom, shapeIndexFrom, shapeObjectTo, shapeIndexTo, test=1)
                   
                 #print self.Tubes[index]['nleft'], " - " , self.Tubes[index]['tleft']
                 if not(self.Tubes[index]['nleft']==-1) and (self.Tubes[index]['tleft']=="atmosphere"): # a la derecha una atmosphere
                     shapeObjectTo = shapeList[i]
                     shapeIndexTo = i
                     (shapeObjectFrom,shapeIndexFrom) = self.findShape("Atmospheres",self.Tubes[index]['nleft'])              
                     self.makeConection(shapeObjectFrom, shapeIndexFrom, shapeObjectTo, shapeIndexTo, test=1)

             if element == "Junctions":
                 j = 0
                 for t in self.Junctions[index]['type_end']:
                     shapeObjectFrom = shapeList[i]
                     shapeIndexFrom = i
                     if t==-1: #de escape, es decir a izquierda
                         (shapeObjectTo,shapeIndexTo) = self.findShape("Tubes",self.Junctions[index]['node2tube'][j]) 
                         self.makeConection(shapeObjectFrom, shapeIndexFrom, shapeObjectTo, shapeIndexTo, test=1)
                     j = j+1

             if element == "Tanks":
                 j = 0
                 for t in self.Tanks[index]['exh2tube']:
                     shapeObjectFrom = shapeList[i]
                     shapeIndexFrom = i
                     (shapeObjectTo,shapeIndexTo) = self.findShape("Tubes",self.Tanks[index]['exh2tube'][j]) 
                     self.makeConection(shapeObjectFrom, shapeIndexFrom, shapeObjectTo, shapeIndexTo, test=1)
                     j = j+1
               
             if element == "Cylinders":
                 j = 0
                 for t in self.Cylinders[index]['exhaust_valves']:
                     shapeObjectFrom = shapeList[i]
                     shapeIndexFrom = i
                     Valve = self.Cylinders[index]['exhaust_valves'][j]
                     (shapeObjectTo,shapeIndexTo) = self.findShape("Valves",Valve) #busco la valve que sea identica
                     self.makeConection(shapeObjectFrom, shapeIndexFrom, shapeObjectTo, shapeIndexTo, test=1)
                     j = j+1

             if element == "Valves":
                 if self.Valves[index]['typeVal'] == "exh" and not(self.Valves[index]['tube']==-1):
                     shapeObjectFrom = shapeList[i]
                     shapeIndexFrom = i
                     (shapeObjectTo,shapeIndexTo) = self.findShape("Tubes",self.Valves[index]['tube']) 
                     self.makeConection(shapeObjectFrom, shapeIndexFrom, shapeObjectTo, shapeIndexTo, test=1) 
                 if self.Valves[index]['typeVal'] == "int" and not(self.Valves[index]['ncyl']==-1):
                     shapeObjectFrom = shapeList[i]
                     shapeIndexFrom = i
                     (shapeObjectTo,shapeIndexTo) = self.findShape("Cylinders",self.Valves[index]['ncyl']) 
                     self.makeConection(shapeObjectFrom, shapeIndexFrom, shapeObjectTo, shapeIndexTo, test=1)
             i = i+1

         return

    def findShape(self,nameElement, index):
        shapeList = self.canvas.GetDiagram().GetShapeList()
        i = 0
        #print "Buscando"
        for s in self.shapes:
            #print s[0]," - ",nameElement
            #print s[1]," - ",index
            if nameElement in ["Tanks","Tubes","Junctions","Atmospheres","Cylinders"]:
                if s[0] == nameElement and s[1] == index:
                   return (shapeList[i],i)
            if nameElement == "Valves":
                if isinstance(index,int): #conexion tube-valve
                   if s[0] == nameElement and self.Valves[s[1]]['tube'] == index:
                       return (shapeList[i],i)
                else: #conexion cylinder - valve
                   if s[0] == nameElement:
                       if self.Valves[s[1]] == index: #aca le habia enviado la instancia valve para comparar
                           return (shapeList[i],i)
            i = i+1  
        return (-1,-1)
        
    # verifica si es posible realizar la conexion, si lo es, llama a conectar
    # From a la izquierda, To a la derecha
    def possibleConnection(self, shapeFrom, shapeTo):
        elementFrom = shapeFrom[0]
        indexFrom   = shapeFrom[1]
        elementTo   = shapeTo[0]
        indexTo     = shapeTo[1]
       
        if elementFrom == "Tubes":

            if self.Tubes[indexFrom]['nright'] == -1: 
                if elementTo == "Tubes":
                    if self.Tubes[indexTo]['nleft'] == -1:      
                        self.initConnections(elementFrom,indexFrom,elementTo,indexTo)
                        return 1
                    else:
                        return "The tube already has connections at left"
                if elementTo in ["Atmospheres", "Junctions", "Tanks"]: #aceptan muchas conexiones
                    self.initConnections(elementFrom,indexFrom,elementTo,indexTo)
                    return 1
                
                if elementTo == "Cylinders":
                    return "The Tube needs be connected with a Valve, not with a Cylinder" 

                if elementTo == "Valves":
                    if self.Valves[indexTo]['ncyl'] == -1 or not(self.Valves[indexTo]['typeVal']=='int'):
                        return "For connect a Tube with a Valve, you need first connect a Intake Valve with a Cylinder"                        
                    if not(self.Valves[indexTo]['tube']==-1):
                        return "The valve already is connected with another tube"
                    if not(self.Valves[indexTo]['type']==0):
                        return "The valve must be for Intake"
                    self.initConnections(elementFrom,indexFrom,elementTo,indexTo)
                    return 1

            else:
                return "The tube already has connections at right" 

        if elementFrom in  ["Atmospheres", "Junctions", "Tanks"]:
            if elementTo == "Tubes":
                if self.Tubes[indexTo]['nleft'] == -1:
                    self.initConnections(elementFrom,indexFrom,elementTo,indexTo)
                    return 1
                else: 
                    return "The tube already has connections at left"
            else:
                return "This element only can connect with tubes" 

        if elementFrom == "Cylinders":
            if elementTo == "Valves":
                if not(self.Valves[indexTo]['type']==1):
                    return "The valve must be for Exhaust"
                if self.Valves[indexTo]['ncyl'] == -1: #el cilindro permite multiples valvulas, pero cada valvula solo es de 1 cilindro
                    self.initConnections(elementFrom,indexFrom,elementTo,indexTo)
                    return 1
                else:
                    return "The valve already is connected with another cylinder"  
            else:
                return "This element only can connect with valves"  
       
        if elementFrom == "Valves":
            if elementTo == "Cylinders":
                if not(self.Valves[indexFrom]['type']==0):
                    return "The valve must be for Intake"
                if self.Valves[indexFrom]['ncyl'] == -1:
                    self.initConnections(elementFrom,indexFrom,elementTo,indexTo)
                    return 1
                else:
                    return "The valve already is connected with another cylinder" 
            if elementTo == "Tubes":
                #print len(self.Valves)," - ",indexFrom
                if not(self.Valves[indexFrom]['type']==1):
                    return "The valve must be for Exhaust"
                if self.Valves[indexFrom]['ncyl'] == -1 or not(self.Valves[indexFrom]['typeVal']=='exh'):
                    return "For connect a Valve with a Tube, you need first connect a Cylinder with a Exhaust Valve"
                if not(self.Valves[indexFrom]['tube'] == -1):
                    return "The valve already is connected with another tube"
                else:
                    if self.Tubes[indexTo]['nleft'] == -1:
                        self.initConnections(elementFrom,indexFrom,elementTo,indexTo)
                        return 1
                    else:
                        return "The tube already has connections at left"     
            return "This element only can connect with Cylinders or Tubes"  


        return 1

     # inicializa las variables de conexion de cualquier tipo de componente
     # NO corroborra si es correcto, solo asigna!!
     # si se quiere setear una conexion, los argumentos optativos deben enviarse    
    def initConnections(self, elementFrom, indexFrom, elementTo="<none>", indexTo=-1 ):
        if elementFrom == "Tubes":

            if elementTo == "Valves":
                self.Tubes[indexFrom]['nright'] = self.Valves[indexTo]['ncyl']
                self.Tubes[indexFrom]['tright'] = "cylinder"
            else:#si vienen los valores por defecto inicializo las conexiones (tmb entra en else)
                nameElementTo = default_values.giveMeNames[elementTo]
                self.Tubes[indexFrom]['nright'] = indexTo
                self.Tubes[indexFrom]['tright'] = nameElementTo

            if elementTo == "<none>":
                self.Tubes[indexFrom]['nleft'] = indexTo
                self.Tubes[indexFrom]['tleft'] = nameElementTo
            if elementTo == "Junctions":
                self.Junctions[indexTo]['node2tube'].append(indexFrom)
                self.Junctions[indexTo]['type_end'].append(1) #admision
                self.Junctions[indexTo]['nnod'] = len(self.Junctions[indexTo]['node2tube'])
            if elementTo == "Tanks":
                self.Tanks[indexTo]['int2tube'].append(indexFrom) #admision
                self.Tanks[indexTo]['nnod'] = len(self.Tanks[indexTo]['int2tube']) + len(self.Tanks[indexTo]['exh2tube']) + 1 
            if elementTo == "Valves":
                self.Valves[indexTo]['tube'] = indexFrom
            if elementTo == "Tubes":
                self.Tubes[indexTo]['nleft'] = indexFrom
                self.Tubes[indexTo]['tleft'] = "tube"
            # para atmospheres no hago nada!


        if elementFrom in ["Atmospheres","Tanks","Junctions"]: #El tube se conecta de la misma forma a c/u de estos

            if not(elementTo=="<none>"):
                self.Tubes[indexTo]['nleft'] = indexFrom
                self.Tubes[indexTo]['tleft'] = default_values.giveMeNames[elementFrom]

            if elementFrom == "Tanks":
                if elementTo=="<none>": #inicializo las conexiones
                    self.Tanks[indexFrom]['int2tube'] = []  
                    self.Tanks[indexFrom]['exh2tube'] = []
                else:
                    self.Tanks[indexFrom]['exh2tube'].append(indexTo)
                    self.Tanks[indexFrom]['nnod'] = len(self.Tanks[indexFrom]['int2tube']) + len(self.Tanks[indexFrom]['exh2tube']) + 1

            if elementFrom == "Junctions":
                if elementTo=="<none>": #inicializo las conexiones
                    self.Junctions[indexFrom]['node2tube'] = []  
                    self.Junctions[indexFrom]['type_end']  = []
                else:
                    self.Junctions[indexFrom]['node2tube'].append(indexTo)
                    self.Junctions[indexFrom]['type_end'].append(-1) #escape
                    self.Junctions[indexFrom]['nnod'] = len(self.Junctions[indexFrom]['node2tube'])
                
        if elementFrom == "Cylinders":
            if not(elementTo=="<none>"): #no requiere inicializar las conexiones
                self.Valves[indexTo]['ncyl'] = indexFrom
                self.Valves[indexTo]['typeVal'] = "exh" #la declaro de escape
                #self.Cylinders[indexFrom]['nnod'] = self.Cylinders[indexFrom]['nnod'] + 1

        if elementFrom == "Valves":
            if elementTo=="<none>": #inicializa sin conectarse a ningun cilindro
                self.Valves[indexFrom]['ncyl'] = -1
                self.Valves[indexFrom]['typeVal'] = "<none>"
                self.Valves[indexFrom]['tube'] = -1
            else:
                if elementTo == "Cylinders":
                    self.Valves[indexFrom]['ncyl'] = indexTo  # va a pertenecer al cilindro clickeado
                    self.Valves[indexFrom]['typeVal'] = "int" #la declaro de admision
                    #self.Cylinders[indexTo]['nnod'] = self.Cylinders[indexTo]['nnod'] + 1
                if elementTo == "Tubes":
                    self.Valves[indexFrom]['tube'] = indexTo
                    self.Tubes[indexTo]['tleft'] = "cylinder"
                    self.Tubes[indexTo]['nleft'] = self.Valves[indexFrom]['ncyl']

    def OnKeyUp(self, evt):
        print "key down"
        #if self.logKeyDn:
        #    self.GetParent().keylog.LogKeyEvent("KeyDown", evt)
        #if self.callSkip:
        #    evt.Skip()

    #manejador de eventos de teclado
    def OnKeyDown(self, evt):
        print 'key up'
        keycode = evt.GetKeyCode()
        keyname = keyMap.get(keycode, None)
        if keyname is None:
            if keycode < 256:
                if keycode == 0:
                    keyname = "NUL"
                elif keycode < 27:
                    keyname = "Ctrl-%s" % chr(ord('A') + keycode-1)
                else:
                    keyname = "\"%s\"" % chr(keycode)
            else:
                keyname = "(%s)" % keycode
        
        # print evt.ControlDown(), keyname

        #evento de copia (solo para componentes)
        if(evt.ControlDown() and keyname=='"C"'):
            self.OnMenuEditCopy("")

        if keycode==wx.WXK_DELETE or (evt.ControlDown() and keyname=='"X"'):
            # print "eliminar seleccionado"
            self.OnMenuEditDelete("")

        if(evt.ControlDown() and keyname=='"V"'):
            self.OnMenuEditPaste("")


    def OnChar(self, evt):
        print "onchar"
        #if self.logChar:
        #    self.GetParent().keylog.LogKeyEvent("Char", evt)

    def findSelected(self):
        shapeList = self.canvas.GetDiagram().GetShapeList()
        indexShapes = 0
        indexLines = 0
        for s in shapeList:

            if s.Selected():
                if isinstance(s,ogl.BitmapShape):
                    return (s,indexShapes)
                else:
                    return (s,indexLines)

            if isinstance(s,ogl.BitmapShape):
                indexShapes = indexShapes + 1
            else:
                indexLines = indexLines + 1

        return (-1,-1) # no hay ninguna seleccionada

    #retorna "1" en caso de que el elemento no tenga conexiones, "0" en caso de que tenga al menos una
    def canDeleteShape(self,index):
        (element,indexElem) = self.shapes[index]
        
        if element == "Cylinders": #busco que alguna valve este conectada a el
            for v in self.Valves:
                if v['ncyl'] == indexElem:
                    return 0
            return 1

        if element == "Valves": #conectada a algun cilindro o tube
            if self.Valves[indexElem]['ncyl'] == -1 and self.Valves[indexElem]['tube'] == -1:
                return 1
            else:
                return 0

        if element == "Tubes": #conectado a algo
            if self.Tubes[indexElem]['nleft'] == -1 and self.Tubes[indexElem]['nright'] == -1:
                return 1
            else:
                return 0
   
        if element == "Junctions": #si la lista esta vacia entonces esta desconectada
            if len(self.Junctions[indexElem]['node2tube']) == 0:
                return 1
            else:
                return 0 

        if element == "Atmospheres": #si ningun tube a referencia entonces esta desconectada
            for t in self.Tubes:
                if (t['tleft'] == "atmosphere" and t['nleft'] == indexElem) or (t['tright'] == "atmosphere" and t['nright'] == indexElem):
                    return 0
            return 1

        if element == "Tanks": #si las listas de admision y escape estan vacias entonces esta desconectado
            if len(self.Tanks[indexElem]['exh2tube']) == 0 and len(self.Tanks[indexElem]['int2tube']) == 0:
                return 1
            else:
                return 0

    #retorna "1" en caso de que el elemento no tenga conexiones, "0" en caso de que tenga al menos una
    def canDeleteLine(self,index):
        (indexShapeFrom, indexShapeTo) = self.connectionLines[index]
        (elementFrom, indexFrom) = self.shapes[indexShapeFrom]
        (elementTo, indexTo) = self.shapes[indexShapeTo]
        
        if elementFrom == "Valves" and elementTo == "Cylinders" and not(self.Valves[indexFrom]['tube'] == -1):
            return 0
        if elementFrom == "Cylinders" and elementTo == "Valves" and not(self.Valves[indexTo]['tube'] == -1):
            return 0
        return 1

    #elimina el elemento, tanto del diagrama, como de los datos internos, ademas se deben actualizar las conexiones
    def deleteShape(self,index, shapeObject):
        (element,indexElem) = self.shapes[index]

        if element == "Cylinders":
            del self.Cylinders[indexElem]
            for t in self.Tubes:
                if t['tleft'] == "cylinder" and t['nleft'] > indexElem: #me quedaria desfasado
                    t['nleft'] = t['nleft'] - 1
                if t['tright'] == "cylinder" and t['nright'] > indexElem: #me quedaria desfasado
                    t['nright'] = t['nright'] - 1
            for v in self.Valves:
                if v['ncyl'] > indexElem:
                    v['ncyl'] = v['ncyl'] - 1

        if element == "Valves":
            del self.Valves[indexElem]

        if element == "Tubes":
            del self.Tubes[indexElem]
            for j in self.Junctions:
                for n2t in range(len(j['node2tube'])):
                    if j['node2tube'][n2t] > indexElem:
                        j['node2tube'][n2t] = j['node2tube'][n2t] - 1
            for t in self.Tanks:
                for i2t in range(len(t['int2tube'])):
                    if t['int2tube'][i2t] > indexElem:
                        t['int2tube'][i2t] = t['int2tube'][i2t] - 1
                for e2t in range(len(t['exh2tube'])):
                    if t['exh2tube'][e2t] > indexElem:
                        t['exh2tube'][e2t] = t['exh2tube'][e2t] - 1
            for v in self.Valves:
                if v['tube'] > indexElem:
                        v['tube'] = v['tube'] - 1

        if element == "Junctions":
            del self.Junctions[indexElem]
            for t in self.Tubes:
                if t['tleft'] == "junction" and t['nleft'] > indexElem: #me quedaria desfasado
                    t['nleft'] = t['nleft'] - 1
                if t['tright'] == "junction" and t['nright'] > indexElem: #me quedaria desfasado
                    t['nright'] = t['nright'] - 1
            
        if element == "Atmospheres":
            del self.Atmospheres[indexElem]
            for t in self.Tubes:
                if t['tleft'] == "atmosphere" and t['nleft'] > indexElem: #me quedaria desfasado
                    t['nleft'] = t['nleft'] - 1
                if t['tright'] == "atmosphere" and t['nright'] > indexElem: #me quedaria desfasado
                    t['nright'] = t['nright'] - 1

        if element == "Tanks": 
            del self.Tanks[indexElem]
            for t in self.Tubes:
                if t['tleft'] == "tanks" and t['nleft'] > indexElem: #me quedaria desfasado
                    t['nleft'] = t['nleft'] - 1
                if t['tright'] == "tanks" and t['nright'] > indexElem: #me quedaria desfasado
                    t['nright'] = t['nright'] - 1
        
        #actualizo indices de conexion y las referencias de shapes
        del self.shapes[index]
        for s in range(len(self.shapes)):
            #print "En shapes: ", self.shapes[s]
            (nameElement, indexElement) = self.shapes[s]
            if nameElement == element and indexElement >= indexElem:
                indexElement = indexElement - 1
            self.shapes[s] = (nameElement, indexElement)
       
        for cl in range(len(self.connectionLines)):
            (cl0,cl1) = self.connectionLines[cl]
            if cl0 > index:
                cl0 = cl0 - 1
            if cl1 > index:
                cl1 = cl1 - 1
            self.connectionLines[cl] = (cl0,cl1)

        #elimino de mi lista interna, de la del diagrama y ademas los puntos de control
        
        shapeList = self.diagram.GetShapeList()
        toDelete = [shapeObject]
        for s in shapeList:
           #print type(s)
           if isinstance(s,ogl.ControlPoint):
               toDelete.append(s)

        for s in toDelete:
           self.diagram.RemoveShape(s)

        self.canvas.Refresh(True)
        #print "tamanio shapes: ",len(self.shapes)
        #print "tamanio lineas: ",len(self.connectionLines)
        #print "tamanio diagram: ",self.diagram.GetCount()
        self.saved = 0

        #elimino el objeto del arbol, y actualizo las referencias
        toDelete = self.itemsTree[element][indexElem]
        for c in self.itemsTree[element]:
            if int(c) > indexElem:
                peer = self.tree.GetItemPyData(self.itemsTree[element][c])
                p0 = peer[0]
                p1 = peer[1] - 1
                peer = (p0,p1)	
                self.tree.SetItemData(self.itemsTree[element][c],peer)
                i = int(c) - 1
                self.itemsTree[element][i] = self.itemsTree[element][c]
        self.tree.Delete(toDelete)        


    #elimino las conexiones, atencion en la actualizacion de nnod 
    def deleteLine(self,index, shapeObject):
        #print "eliminando lines: ",self.connectionLines[index]
        (indexShapeFrom, indexShapeTo) = self.connectionLines[index]
        (elementFrom, indexFrom) = self.shapes[indexShapeFrom]
        (elementTo, indexTo) = self.shapes[indexShapeTo]
        
        #if elementFrom == "Cylinders":
        #    self.Cylinders[indexFrom]['nnod'] = self.Cylinders[indexFrom]['nnod'] - 1

        if elementFrom == "Valves":
            if self.Valves[indexFrom]['typeVal'] == 'int':
                self.Valves[indexFrom]['ncyl'] = -1
            else:
                self.Valves[indexFrom]['tube'] = -1

        if elementFrom == "Tubes":
            self.Tubes[indexFrom]['nright'] = -1
            self.Tubes[indexFrom]['tright'] = "<none>"

        if elementFrom == "Junctions":
            i = self.Junctions[indexFrom]['node2tube'].index(indexTo)
            del self.Junctions[indexFrom]['node2tube'][i]
            del self.Junctions[indexFrom]['type_end'][i]
            self.Junctions[indexFrom]['nnod'] = len(self.Junctions[indexFrom]['node2tube'])

        if elementFrom == "Tanks":
            self.Tanks[indexFrom]['exh2tube'].remove(indexTo)
            self.Tanks[indexFrom]['nnod'] = len(self.Tanks[indexFrom]['exh2tube']) + len(self.Tanks[indexFrom]['int2tube']) + 1

        #if elementTo == "Cylinders":
        #    self.Cylinders[indexTo]['nnod'] = self.Cylinders[indexTo]['nnod'] - 1

        if elementTo == "Valves":
            if self.Valves[indexTo]['typeVal'] == 'exh':
                self.Valves[indexTo]['ncyl'] = -1
            else:
                self.Valves[indexTo]['tube'] = -1

        if elementTo == "Tubes":
            self.Tubes[indexTo]['nleft'] = -1
            self.Tubes[indexTo]['tleft'] = "<none>"

        if elementTo == "Junctions":
            i = self.Junctions[indexTo]['node2tube'].index(indexFrom)
            del self.Junctions[indexTo]['node2tube'][i]
            del self.Junctions[indexTo]['type_end'][i]
            self.Junctions[indexTo]['nnod'] = len(self.Junctions[indexTo]['node2tube'])

        if elementTo == "Tanks": 
            self.Tanks[indexTo]['int2tube'].remove(indexFrom)
            self.Tanks[indexTo]['nnod'] = len(self.Tanks[indexFrom]['exh2tube']) + len(self.Tanks[indexFrom]['int2tube']) + 1

        del self.connectionLines[index]
        
        #elimino tambien los puntos de control
        shapeList = self.diagram.GetShapeList()
        toDelete = [shapeObject]
        for s in shapeList:
           #print type(s)
           if isinstance(s,ogl.ControlPoint):
               toDelete.append(s)

        for s in toDelete:
           self.diagram.RemoveShape(s)

        self.canvas.Refresh(True)
        #print "tamanio shapes: ",len(self.shapes)
        #print "tamanio lineas: ",len(self.connectionLines)
        #print "tamanio diagram: ",self.diagram.GetCount()
        self.saved = 0

    def findTubesNames(self,indexs):
        labels = []
        for i in indexs:
            labels.append(self.Tubes[i]['label'])
        return labels

    # antes de correr se comprueba si todos los componentes estan conectados
    # falta comprobar los cylinders
    def hasDisconnections(self):
        disconnected = []

        for t in self.Tubes:
            if t['nleft'] == -1 or t['nright'] == -1:
                disconnected.append(t['label'])

        for j in self.Junctions:
            has_in = 0
            has_exh = 0
            for t in j['type_end']:
                if t==1:
                    has_in = 1
                else:
                    has_exh = 1
            if has_in == 0 or has_exh == 0:
                disconnected.append(j['label'])

        for t in self.Tanks:
            if len(t['int2tube']) == 0 or len(t['exh2tube']) == 0:
                disconnected.append(t['label'])

        for v in self.Valves:
            if v['tube'] == -1 or v['ncyl'] == -1:
                disconnected.append(v['label'])

        return disconnected

####--------------------------------------------####

# ---  END DIAGRAM CONTROL CODE -----#

####--------------------------------------------####

####--------------------------------------------####

# ---  BEGIN TREE CONTROL CODE -----#

####--------------------------------------------####

    def OnRightDown(self, event):
        pt = event.GetPosition();
        item, flags = self.tree.HitTest(pt)
        if item:
            #self.log.WriteText("OnRightClick: %s, %s, %s\n" %
            #                   (self.tree.GetItemText(item), type(item), item.__class__))
            self.tree.SelectItem(item)


    def OnRightUp(self, event):
        pt = event.GetPosition();
        item, flags = self.tree.HitTest(pt)
        if item:        
            #self.log.WriteText("OnRightUp: %s (manually starting label edit)\n"
            #                   % self.tree.GetItemText(item))
            self.tree.EditLabel(item)


    def OnLeftDClick(self, event):
        pt = event.GetPosition();
        item, flags = self.tree.HitTest(pt)
        if item:
            peer = self.tree.GetItemPyData(item)
            if peer[0] == "Cylinders":
                self.OnStatusBarCylinder("", peer[1])
            if peer[0] == "Junctions":
                self.OnStatusBarJunction("", peer[1])
            if peer[0] == "Tubes":
                self.OnStatusBarTube("", peer[1])
            if peer[0] == "Tanks":
                self.OnStatusBarTank("", peer[1])
            if peer[0] == "Atmospheres":
                self.OnStatusBarAtmosphere("", peer[1])
            if peer[0] == "Valves":
                self.OnStatusBarValve("", peer[1])

    def OnSize(self, event):
        w,h = self.GetClientSizeTuple()
        self.tree.SetDimensions(0, 0, w, h)


    def OnItemExpanded(self, event):
        item = event.GetItem()
        #if item:
        #    self.log.WriteText("OnItemExpanded: %s\n" % self.tree.GetItemText(item))

    def OnItemCollapsed(self, event):
        item = event.GetItem()
        #if item:
            #self.log.WriteText("OnItemCollapsed: %s\n" % self.tree.GetItemText(item))

    def OnSelChanged(self, event):
        self.item = event.GetItem()
        #if self.item:
            #self.log.WriteText("OnSelChanged: %s\n" % self.tree.GetItemText(self.item))
            #if wx.Platform == '__WXMSW__':
            #    self.log.WriteText("BoundingRect: %s\n" %
            #                      self.tree.GetBoundingRect(self.item, True))
            #items = self.tree.GetSelections()
            #print map(self.tree.GetItemText, items)
        event.Skip()


    def OnActivate(self, event):
        pass
        #if self.item:
            #self.log.WriteText("OnActivate: %s\n" % self.tree.GetItemText(self.item))

    def initTree(self):
        self.childs = dict()
        for name in self.names:
            self.itemsTree[name] = dict()
            self.childs[name] = self.tree.AppendItem(self.root, name)
            self.tree.SetItemData(self.childs[name], None)
            self.tree.SetItemImage(self.childs[name], self.fldridx, wx.TreeItemIcon_Normal)
            self.tree.SetItemImage(self.childs[name], self.fldropenidx, wx.TreeItemIcon_Expanded)

    def addItemTree(self,element,index,label="ssaas"):
        last = self.tree.AppendItem(self.childs[element],label)
        self.tree.SetItemData(last, None)
        peer = (element,index)
        self.tree.SetItemData(last,peer)
        self.itemsTree[element][index] = last
        self.tree.SetItemImage(last, self.tipdx, wx.TreeItemIcon_Normal)

    def deleteItemTree(self,element,index):
        self.tree.Delete(self.itemsTree[element][index])

    def getLabel(self,element,index):
        if element == "Tubes":
            return self.Tubes[index]['label']
        if element == "Junctions":
            return self.Junctions[index]['label']
        if element == "Tanks":
            return self.Tanks[index]['label']
        if element == "Cylinders":
            return self.Cylinders[index]['label']
        if element == "Valves":
            return self.Valves[index]['label']
        if element == "Atmospheres":
            return "atmosp_"+str(len(self.Atmospheres))

# end of class Home


