# -*- 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
#
#-------------------------------------------------------------------------------


"""
This module defines the storage system type.

This module contains the following classes and function:
- MatisseHydrauModel
- MatisseHydrauView
- PageText
"""


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


import Tix
from Tkconstants import *
import sys, unittest


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


from Base.Common import *
import Base.Toolbox as Tool
import Base.TkPage as TkPage
import Pages.MatisseType as MatisseType


#-------------------------------------------------------------------------------
# Turbulence model class
#-------------------------------------------------------------------------------


class MatisseHydrauModel:
    """
    Manage the input/output markups in the xml doc about matisse hydraulic load
    """
    def __init__(self, case):
        """
        Constructor.
        """
        self.case               = case
        self.node_matisse       = self.case.root().xmlInitChildNode('matisse')
        self.node_compute       = self.node_matisse.xmlInitChildNode('compute')
        self.node_phymodel      = self.node_compute.xmlInitChildNode('physical_model')

        self.node_cofor         = self.node_phymodel.xmlInitChildNode('icofor','status')
        self.node_conlg         = self.node_phymodel.xmlInitChildNode('iconlg','status')
        
        self.status = ('on', 'off')


    def defaultMatisseHydrauValues(self):
        """
        Return in a dictionnary which contains default values
        """
        default = {}
        #
        # bool
        default['icofor'] = 'off'
        default['iconlg'] = 'off'

        #
        # double
        default['debmas'] = 0.
        default['pdccha'] = 1.7
        default['pdcfch'] = 0.
        default['dhchea'] = 1.7
        default['sdchea'] = 3.2
        default['pdcche'] = 2.
        default['pdccch'] = 0.
        default['dhches'] = 1.2
        default['sdches'] = 3.82
        default['pdcalg'] = 0.25
        default['pdcatv'] = 0.25
        default['argamt'] = 0.
        default['pdcslg'] = 0.25
        default['pdcstv'] = 0.25
        default['argavl'] = 0.
        default['amppdc'] = 1.
        default['dhalve'] = 0.13
        default['dpvent'] = 0.
        
        return default


    def setMatisseHydrauVar(self, tag, val):
        """
        """
        self.node_phymodel.xmlSetData(tag, val)


    def getMatisseHydrauDoubleVar(self, tag):
        """
        """
        val = self.node_phymodel.xmlGetDouble(tag)

        if val == "" or val == None:
            self.node_phymodel.xmlInitChildNode(tag)
            val = self.defaultMatisseHydrauValues()[tag]
            self.setMatisseHydrauVar(tag, val)

        return val


    def setConstrainedConvStatus(self, stat):
        """
        Input constrained convection status
        """
        if stat not in self.status :
            sys.exit(1)

        self.node_cofor['status'] = stat


    def getConstrainedConvStatus(self):
        """
        Return constrained convection status
        """
        stat = self.node_cofor['status']
            
        if stat not in self.status :
            stat = self.defaultMatisseHydrauValues()['icofor']
            self.setConstrainedConvStatus(stat)
        return stat


    def setInlineContainerNetworkStatus(self, stat):
        """
        Input containers network in line status
        """
        if stat not in self.status :
            sys.exit(1)

        self.node_conlg['status'] = stat


    def getInlineContainerNetworkStatus(self):
        """
        Return containers network in line status
        """
        stat = self.node_conlg['status']
            
        if stat not in self.status :
            stat = self.defaultMatisseHydrauValues()['iconlg']
            self.setInlineContainerNetworkStatus(stat)
        return stat


#-------------------------------------------------------------------------------
# Main view class
#-------------------------------------------------------------------------------


class MatisseHydrauView(TkPage.Page):
    """
    Class to open Matisse Page.
    """
    def _tkControlVariables(self):
        """
        Tkinter variables declaration.
        """
        #
        # String Var
        self.icofor = Tix.StringVar()
        self.iconlg = Tix.StringVar()

        #
        # Double Var
        self.debmas = Tix.DoubleVar() 
        self.pdccha = Tix.DoubleVar()
        self.pdcfch = Tix.DoubleVar()
        self.dhchea = Tix.DoubleVar()
        self.sdchea = Tix.DoubleVar()
        self.pdcche = Tix.DoubleVar()
        self.pdccch = Tix.DoubleVar()
        self.dhches = Tix.DoubleVar()
        self.sdches = Tix.DoubleVar()
        self.pdcalg = Tix.DoubleVar()
        self.pdcatv = Tix.DoubleVar()
        self.argamt = Tix.DoubleVar()
        self.pdcslg = Tix.DoubleVar()
        self.pdcstv = Tix.DoubleVar()
        self.argavl = Tix.DoubleVar()
        self.amppdc = Tix.DoubleVar()
        self.dhalve = Tix.DoubleVar()
        self.dpvent = Tix.DoubleVar()


        #
        # association between tix variable and tag

        self.variables=[
            ('debmas',self.debmas),
            ('pdccha',self.pdccha),
            ('pdcfch',self.pdcfch),
            ('dhchea',self.dhchea),
            ('sdchea',self.sdchea),
            ('pdcche',self.pdcche),
            ('pdccch',self.pdccch),
            ('dhches',self.dhches),
            ('sdches',self.sdches),
            ('pdcalg',self.pdcalg),
            ('pdcatv',self.pdcatv),
            ('argamt',self.argamt),
            ('pdcslg',self.pdcslg),
            ('pdcstv',self.pdcstv),
            ('argavl',self.argavl),
            ('amppdc',self.amppdc),
            ('dhalve',self.dhalve),
            ('dpvent',self.dpvent)]


    def ActiveWidget(self, i , stat) :
        if stat == 'off':
            self.e[i].config(state=DISABLED, fg='grey')
            self.e[i].unbind("<<Event>>")
            self.l1[i].config(fg='grey')
            self.l2[i].config(fg='grey')
            try:
                self.l3[i].config(fg='grey')
            except:
                pass
        else :
            self.e[i].config(state=NORMAL, fg='black')
            self.e[i].event_add("<<Event>>", "<Return>", "<Leave>", "<FocusOut>")
            self.e[i].bind("<<Event>>",TkPage.Callback(self.getMatisseHydrauVar, i, self.variables[i]))
            self.l1[i].config(fg='black')
            self.l2[i].config(fg='black')
            try:
                self.l3[i].config(fg='black')
            except:
                pass


    def _pageControl(self):
        """
        Instantiate the matisse type modelling class.
        """
        self.model = MatisseHydrauModel(self.case)
        self.model_mat_type = MatisseType.MatisseTypeModel(self.case)


    def getMatisseHydrauVar(self, i, variable, event=None):
        """
        Input hydraulic load variable.
        """
        tag=variable[0]
        var=variable[1]
        
        self.stbar.busy()

        if not (self.e[i].cget('state') == DISABLED) :

            if self.check2.hasType(self.e[i], var):
                t = var.get()
                self.model.setMatisseHydrauVar(tag,t)
            
        self.stbar.idle()

 
    def getConstrainedConvStatus(self, event=None):
        """
        Input constrained convection status.
        """
        
        self.stbar.busy()

        stat = self.icofor.get()
        self.model.setConstrainedConvStatus(stat)

        self.ActiveWidget(0,stat)

        self.stbar.idle()


    def getInlineContainerNetworkStatus(self, event=None):
        """
        Input In line container network status.
        """
        
        self.stbar.busy()

        stat = self.iconlg.get()
        self.model.setInlineContainerNetworkStatus(stat)

        self.stbar.idle()


    def _createWidgets(self):
        """
        Create the Page layout.
        """
        t = PageText()

        lf = Tix.LabelFrame(self.myPage, bd=2, label=t.MATISSE_HYDRAU_TITLE, relief=FLAT)
        lf.label.config(font=fT)
        lf.pack(side=TOP, fill=X, padx=10, pady=10)

        self.w1 = Tix.Frame(lf.frame, relief=FLAT)
        self.w1.pack(side=TOP, fill=X, pady=10)

        # Separator
        #
        s1 = Tix.Frame(lf.frame, height=2, bd=2, relief=SUNKEN)
        s1.pack(side=TOP, fill=X)

        self.w2 = Tix.Frame(lf.frame, relief=FLAT)
        self.w2.pack(side=TOP, fill=X, pady=10)

        # ICOFOR
        #
        h1 = Tix.Label(self.w1, text=t.texts['icofor'][0])
        h1.grid(row=0, column=0, padx=15, sticky=W)

        h2 = Tix.Label(self.w1, text=t.texts['icofor'][1])
        h2.grid(row=0, column=1, padx=15, sticky=W)


        self.c1 = Tix.Checkbutton(self.w1, onvalue='on', offvalue='off',
                                  variable=self.icofor,
                                  command=self.getConstrainedConvStatus)
        self.c1.grid(row=0, column=2, sticky=E)

        # ICONLG
        #
        h3 = Tix.Label(self.w1, text=t.texts['iconlg'][0])
        h3.grid(row=1, column=0, padx=15, sticky=W)

        h4 = Tix.Label(self.w1, text=t.texts['iconlg'][1])
        h4.grid(row=1, column=1, padx=15, sticky=W)


        self.c2 = Tix.Checkbutton(self.w1, onvalue='on', offvalue='off',
                                  variable=self.iconlg,
                                  command=self.getInlineContainerNetworkStatus)
        self.c2.grid(row=1, column=2, sticky=E)
        
        self.l1=[0]*len(self.variables)
        self.l2=[0]*len(self.variables)
        self.l3=[0]*len(self.variables)
        self.e=[0]*len(self.variables)
        
        for i in range(len(self.variables)):

            variable=self.variables[i]
 
            self.l1[i] = Tix.Label(self.w2, text=t.texts[variable[0]][0])
            self.l1[i].grid(row=i, column=0, padx=2, pady=5, sticky=W)
            self.l2[i] = Tix.Label(self.w2, text=t.texts[variable[0]][1])
            self.l2[i].grid(row=i, column=1, padx=2, pady=5, sticky=W)

            self.e[i] = Tix.Entry(self.w2, width=10, textvariable=variable[1])
            self.e[i].grid(row=i, column=2, padx=3, pady=5)
            self.e[i].event_add("<<Event>>", "<Return>", "<Leave>", "<FocusOut>")
            self.e[i].bind("<<Event>>",TkPage.Callback(self.getMatisseHydrauVar, i, variable))

            try:
                self.l3[i] = Tix.Label(self.w2, text=t.texts[variable[0]][2])
                self.l3[i].grid(row=i, column=3, pady=5, sticky=E)
            except :
                pass

    
    def _initializeWidgets(self):
        """
        Extract resquested informations from XML document.
        This informations are used to initialize the widgets.
        For this page default values of all widgets are necessary
        included in the XML file.
        """


        # Voir ce qui ne va pas
        stat = self.model.getConstrainedConvStatus()
        self.icofor.set(stat)
        self.ActiveWidget(0,stat)
        
        stat = self.model.getInlineContainerNetworkStatus()
        self.iconlg.set(stat)

        i = 0
        for variable in self.variables :
            val = self.model.getMatisseHydrauDoubleVar(variable[0])
            variable[1].set(val)

            if variable[0] == 'dhalve' :
                stat = self.model_mat_type.node_alveo['status']               
                self.ActiveWidget(i,stat)
            i += 1


#-------------------------------------------------------------------------------
# Text and messages for this page
#-------------------------------------------------------------------------------


class PageText:
    """
    Storage of all texts and messages for this page.
    """
    def __init__(self):
        if Tool.GuiParam.lang == 'fr':
            self.MATISSE_HYDRAU_TITLE="Chargement hydraulique"
            self.texts={}
            self.texts['icofor'] = (1,"Régime hydraulique de circulation forcée")
            self.texts['iconlg'] = (2,"Réseau de conteneurs en ligne (pas triangulaire sinon)")
            self.texts['debmas'] = (3,"Débit de circulation forcee","Kg/s")
            self.texts['pdccha'] = (4,"Perte de charge du diffuseur de cheminée d'alimentation")
            self.texts['pdcfch'] = (5,"Perte de charge du filtre de cheminee d'alimentation")
            self.texts['dhchea'] = (6,"Diamètre hydraulique de cheminée d'alimentation","m")
            self.texts['sdchea'] = (7,"Surface débitante de cheminée d'alimentation","m²")
            self.texts['pdcche'] = (8,"Perte de charge du diffuseur de cheminée d'évacuation")
            self.texts['pdccch'] = (9,"Perte de charge du clapet de cheminée d'évacuation")
            self.texts['dhches'] = (10,"Diametre hydraulique de cheminée d'évacuation","m")
            self.texts['sdches'] = (11,"Surface débitante de cheminée d'évacuation","m²")
            self.texts['pdcalg'] = (12,"Perte de charge porte d'entrée amont longitudinal")
            self.texts['pdcatv'] = (13,"Perte de charge porte d'entree amont transversale")
            self.texts['argamt'] = (14,"Angle d'inclinaison du registre aval (degré)","°")
            self.texts['pdcslg'] = (16,"Perte de charge porte de sortie aval longitudinale")
            self.texts['pdcstv'] = (17,"Perte de charge porte de sortie aval transversale")
            self.texts['argavl'] = (18,"Angle d'inclinaison du registre aval (degré)","°")
            self.texts['amppdc'] = (20,"Amplification des pertes de charge de réseau")
            self.texts['dhalve'] = (23,"Diamètre hydraulique de l'alvéole","m")
            self.texts['dpvent'] = (24,"Différentiel de pression athmosphèrique entrée/sortie","Pa")

        else:
            self.MATISSE_HYDRAU_TITLE="hydraulic load"
            self.texts={}
            self.texts['icofor'] = (1,"Forced hydraulic air circulation regime")
            self.texts['iconlg'] = (2,"Canister network in row (staggered arrangement otherwise)")
            self.texts['debmas'] = (3,"Forced circulation air flow","Kg/s")
            self.texts['pdccha'] = (4,"Inlet chimney diffuser headloss")
            self.texts['pdcfch'] = (5,"Inlet chimney filter headloss")
            self.texts['dhchea'] = (6,"Inlet chimney hydraulic diameter","m")
            self.texts['sdchea'] = (7,"Inlet chimney flow area","m²")
            self.texts['pdcche'] = (8,"Outlet chimney diffuser headloss")
            self.texts['pdccch'] = (9,"Outlet chimney valve headloss")
            self.texts['dhches'] = (10,"Outlet chimney hydraulic diameter","m")
            self.texts['sdches'] = (11,"Outlet chimney flow area","m²")
            self.texts['pdcalg'] = (12,"Upstream inlet door longitudinal headloss")
            self.texts['pdcatv'] = (13,"Upstream inlet door transversal headloss")
            self.texts['argamt'] = (14,"Upstream register incline angle (degree)","°")
            self.texts['pdcslg'] = (16,"Downstream outlet door longitudinal headloss")
            self.texts['pdcstv'] = (17,"Downstream outlet door transversal headloss")
            self.texts['argavl'] = (18,"Downstream register incline angle (degree)","°")
            self.texts['amppdc'] = (20,"Network headloss amplifying factor")
            self.texts['dhalve'] = (23,"Double jacketed wells hydraulic diameter","m")
            self.texts['dpvent'] = (24,"Inlet/outlet atmospheric pressure difference","Pa")

#-------------------------------------------------------------------------------
# End
#-------------------------------------------------------------------------------


syntax highlighted by Code2HTML, v. 0.9.1