# -*- coding: iso-8859-1 -*-
#
#-------------------------------------------------------------------------------
#                    Code_Saturne version 1.3
#                    ------------------------
#
#
#     This file is part of the Code_Saturne User Interface, element of the
#     Code_Saturne CFD tool.
#
#     Copyright (C) 1998-2007 EDF S.A., France
#
#     contact: saturne-support@edf.fr
#
#     The Code_Saturne User Interface is free software; you can redistribute it
#     and/or modify it under the terms of the GNU General Public License
#     as published by the Free Software Foundation; either version 2 of
#     the License, or (at your option) any later version.
#
#     The Code_Saturne User Interface is distributed in the hope that it will be
#     useful, but WITHOUT ANY WARRANTY; without even the implied warranty
#     of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#     GNU General Public License for more details.
#
#     You should have received a copy of the GNU General Public License
#     along with the Code_Saturne Kernel; if not, write to the
#     Free Software Foundation, Inc.,
#     51 Franklin St, Fifth Floor,
#     Boston, MA  02110-1301  USA
#
#-------------------------------------------------------------------------------


"""
"""


#-------------------------------------------------------------------------------
# Library modules import
#-------------------------------------------------------------------------------


import sys, os, shutil
import filecmp, os.path


#-------------------------------------------------------------------------------
# Application modules import
#-------------------------------------------------------------------------------


from Base.Common import *
from Base.Toolbox import *
import Pages.InitZone as InitZone
import Pages.BodyForces as BodyForces


#-------------------------------------------------------------------------------
# Global
#-------------------------------------------------------------------------------


class MatisseInit :
    """
    This class is called only by XMLmodel for initializing:
     - Turbulence
     - Gravity
     - Initilization zones
     - Thermal Scalar
     - Additional scalars
     - Properties density , thermal_conductivity, molecular_viscosity
     - MatisseThermicModel
     - MatisseThermUpdate
     - MatisseGeomModel
    """
    def __init__(self, case):

        self.case = case

        #
        # save old geom files
        geomvault = self.case['mesh_path'] +'/vault.geom' 
        geomemm = self.case['mesh_path'] +'/emm.geom'
        try:
            shutil.copyfile(geomvault,geomvault+'~')
        except:
            try:
                shutil.copyfile(geomemm,geomemm+'~')
            except:
                pass
        
        #
        # turbulence
        import Pages.Turbulence as Turbulence
        Turbulence.TurbulenceModel(self.case).setTurbulenceModel("off")
        del Turbulence
        
        #
        # gravity
        model_bodyForce = BodyForces.BodyForcesModel(self.case)
        model_bodyForce.setGravity(2, -9.81)
        model_bodyForce.setHydrostaticPressure('on')

        #
        # Zones initialization
        model_zone = InitZone.InitZoneModel(self.case)
        zones =[["1","0"],["2","2"],["3","3"],["4","4"],
                ["5","6"],["6","7"],["7","8"],["8","9"],["9","10"]]
        for i in range(len(zones)):
            try:
                model_zone.SetZone(i,zones[i][0],zones[i][1])
            except:
                model_zone.NewZone(zones[i][0],zones[i][1])

        #
        # Thermal Scalar
        import Pages.ThermalScalar as ThermalScalar
        thermal = ThermalScalar.ThermalScalarModel(self.case)
        thermal.setThermalScalar('temperature_celsius')
        thermal.node_therm.xmlRemoveChild('initial_value')
        del ThermalScalar

        #
        # Additional scalars
        import Pages.DefineUserScalars as DefineUserScalars
        temp = DefineUserScalars.DefineUserScalarsModel(self.case)

        t = PageText()
        temp.mSetScalar('T_PeauCol', 'Dv1', 0.0, t.NO_VARIANCE, '-1e+12', '1e+12')
        temp.mSetScalar('T_PeauMur', 'Dv2', 0.0, t.NO_VARIANCE, '-1e+12', '1e+12')
        temp.node_user_sca.xmlRemoveChild('initial_value')
        temp.node_user_sca.xmlRemoveChild('variance')
        
        import Pages.UserScalarProperties as UserScalarProperties
        prop = UserScalarProperties.UserScalarPropertiesModel(self.case)
        for node in temp.node_user_sca.xmlGetNodeList('property'):
            prop.msetStatusPrintAndRecordStatus(node,'variable')

        del DefineUserScalars
        del UserScalarProperties
        
        #
        # properties density , thermal_conductivity, molecular_viscosity
        import Pages.FluidCharacteristics as FluidCharacteristics
        fluid = FluidCharacteristics.FluidCharacteristicsModel(self.case)
        fluid.setChoiceNode(fluid.node_density,'variable')
        fluid.setChoiceNode(fluid.node_viscosity,'variable')
        fluid.setChoiceNode(fluid.node_cond,'variable')
        fluid.setChoiceNode(fluid.node_heat,'constant')
        del FluidCharacteristics

        import Pages.MatisseThermic as MatisseThermic
        model = MatisseThermic.MatisseThermicModel(self.case)
        tinit = model.getMatisseThermicDoubleVar('tinit')
        tcrit = model.getMatisseThermicDoubleVar('tcrit')
        MatisseThermUpdate(self.case, tinit, tcrit).compute()
        del MatisseThermic

        from Pages.MatisseGeom import MatisseGeomModel
        MatisseGeomModel(self.case)


class MatisseThermUpdate :
    def __init__(self , case, tinit, tcrit):

        self.case = case
        self.tinit = tinit
        self.tcrit = tcrit

    def compute(self):
        """
        Update XML
        """
        #
        # Thermal Scalar (init)
        import Pages.ThermalScalar as ThermalScalar
        thermal = ThermalScalar.ThermalScalarModel(self.case)

        if self.tinit : thermal.setInitialValue("1", self.tinit)
        if self.tinit : thermal.setInitialValue("2", self.tinit)
        if self.tinit : thermal.setInitialValue("3", self.tinit)
        if self.tinit : thermal.setInitialValue("4", self.tinit)
        if self.tcrit : thermal.setInitialValue("5", self.tcrit)
        if self.tinit : thermal.setInitialValue("6", self.tinit)
        if self.tinit : thermal.setInitialValue("7", self.tinit)
        if self.tinit : thermal.setInitialValue("8", self.tinit)
        if self.tinit : thermal.setInitialValue("9", self.tinit)
        del ThermalScalar

        #
        # Additional Scalars (init)
        import Pages.DefineUserScalars as DefineUserScalars
        temp = DefineUserScalars.DefineUserScalarsModel(self.case)
        import Pages.UserScalarProperties as UserScalarProperties
        prop = UserScalarProperties.UserScalarPropertiesModel(self.case)

        for node in temp.node_user_sca.xmlGetNodeList('scalar'):
            if self.tinit : prop.msetZoneInitialValue(node,"1",self.tinit)
            if self.tinit : prop.msetZoneInitialValue(node,"2",self.tinit)
            if self.tinit : prop.msetZoneInitialValue(node,"3",self.tinit)
            if self.tinit : prop.msetZoneInitialValue(node,"4",self.tinit)
            if self.tinit : prop.msetZoneInitialValue(node,"5",self.tinit)
            if self.tinit : prop.msetZoneInitialValue(node,"6",self.tinit)
            if self.tcrit : prop.msetZoneInitialValue(node,"7",self.tcrit)
            if self.tinit : prop.msetZoneInitialValue(node,"8",self.tinit)
            if self.tinit : prop.msetZoneInitialValue(node,"9",self.tinit)
        
        del DefineUserScalars
        del UserScalarProperties


class MatisseMeshRunning :
    """
    """
    def __init__(self, case):
        """
        """
        self.case = case
        self.ok = True
        #
        # update node <solution_domain> in XML file 
        node_enveloppe  = self.case.root().xmlGetNode('solution_domain')
        node_meshes_list= node_enveloppe.xmlInitChildNode('meshes_list')
        mesh_nodes      = node_meshes_list.xmlGetNodeList('mesh', 'name')

        if len(mesh_nodes) == 1:
            try:
                desFile = mesh_nodes[0]['name'] 
                geomFile = desFile.split(".")[0]+'.geom'
                datFile = desFile.split(".")[0]+'.dat'
            except:
                print "MatisseMeshRunning: see the node mesh"
                sys.exit(1)

            #
            # Files
            newGeom = self.case['mesh_path'] + '/' + geomFile
            oldGeom = self.case['mesh_path'] + '/' + geomFile + '~'
            
            oldDes = self.case['mesh_path']  + '/' + desFile
            datFile = self.case['mesh_path'] + '/' + datFile

            #
            # Checks
            simail = False
            if not os.path.isfile(newGeom) or \
               not os.path.isfile(datFile) or \
               not os.path.isfile(oldDes)  :

                import Pages.MatisseGeom as MatisseGeom 
                MatisseGeom.MatisseGeomModel(self.case).updateMeshAndProbes()
                del MatisseGeom
                simail = True

            else :
                if not os.path.isfile(oldGeom) :
                    simail = True
                else:    
                    if not filecmp.cmp(oldGeom, newGeom):
                        simail = True

            #
            # Simail
            if simail:
                if os.path.isfile(oldDes) :
                    os.remove(oldDes)
                newDes = oldDes
                shutil.copyfile(newGeom, oldGeom)
                os.chdir(self.case['mesh_path'])
                cmd = "xsimail -b " + datFile + " | tee " + self.case['case_path'] + "/RESU/listsim"
                os.system(cmd)
                os.chdir(self.case['case_path'])
                if not os.path.isfile(newDes)  :
                    self.ok = False
            
        else :
            print "MatisseMeshRunning: see meshes_list"
            sys.exit(1)


class PageText:
    """
    Storage of all texts and messages for this page.
    """
    def __init__(self):
        if GuiParam.lang == 'fr':
            self.NO_VARIANCE = "pas de variance"
        else:
            self.NO_VARIANCE = "no variance"


syntax highlighted by Code2HTML, v. 0.9.1