# -*- 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 contains the following classes and function:
- OutputVariableModel
- OutputVarRayView
- ProbeValidator
- VariableOption
"""


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


import string, unittest
import Tix
from Tkconstants import *


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


from Base.Common import *
import Base.Toolbox as Tool
import Base.Dialog as Dialog
import Base.TkPage as TkPage


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


class ProbeValidator(TkPage.DataValidator2):
    """
    """
    def isProbeOK(self, entry, var):
        """
        This method validates the strict Positivity of the value, when an error
        occurs, an exception ValueError is raised.
        """
        try:
            if int(var) <= 0:
                return self._error(entry, ValueError, "value must be positive")
            else:
                return 1
        except:
            return self._error(entry, ValueError, "value must be positive")


#-------------------------------------------------------------------------------
# Output model class
#-------------------------------------------------------------------------------


class OutputVariableModel:

    def __init__(self, case):
        """
        Constuctor
        """
        self.case = case

        self.node_models = self.case.xmlGetNode('thermophysical_models')
        self.node_ray         = self.node_models.xmlInitNode('radiative_transfer')
##        try:
##            self.node_var = node_ray.xmlGetChildNodeList('property')[0]
##        except:
##            self.node_var = []

    def getNodeVar(self, var):
        """
        """
##        return self.node_ray.xmlGetNodeList(var)[0]
        return self.node_ray.xmlGetNode('property',name=var)


    def getNameLabel(self, node):
        """
        """
        if node['label']:
            return node['label']
        else: 
            return node['name']

    def getPostVar(self, node):
        """
        """
        return node['status']


    def setLabelVar(self, node, label):
        """
        """
        node['label'] = label


    def setPostVar(self, node, post):
        """
        """
        node['status'] = post


#-------------------------------------------------------------------------------
# Output class
#-------------------------------------------------------------------------------


class VariableOption:
    """
    """
    def __init__(self, case, master, stbar, balloon, var, node, color):
        """
        """
        self.check = ProbeValidator()

        self.master = master
        self.case   = case
        self.stbar  = stbar
        self.balloon= balloon
        self.name   = var
        self.node   = node
        self.color  = color
        self.balloon = Tix.Balloon(self.master, statusbar=self.stbar.label, bd=1, bg='black')
        self.balloon.message.config(bg=wm['background'])

        self.dicoLabelName = {}
        self.label = Tix.StringVar()
        self.post  = Tix.StringVar()

        self.output = OutputVariableModel(self.case)
        self._createWidgets()


    def _createWidgets(self):
        """
        """
        t = PageText()
        f1 = Tix.Frame(self.master)
        f1.pack()
        
        self.lab = Tix.Entry(f1, width=15, textvariable=self.label, fg=self.color)
        self.lab.event_add("<<Event1>>", "<Return>", "<Leave>")
        self.lab.bind("<<Event1>>", self.getLabel)
        self.balloon.bind_widget(self.lab, balloonmsg=t.KEYWORD+"NBRVAF")
        
        butp = Tix.Checkbutton(f1, onvalue="on", offvalue="off", 
                               variable=self.post, command=self.getPost)
        self.balloon.bind_widget(butp, statusmsg=t.MSG_POST,
                                 balloonmsg=t.KEYWORD+"IRAYVF")
        
        self.lab.grid (row=0, column=0, padx=2, pady=2)
        butp.grid (row=0, column=1, padx=15, pady=2)

        self.label.set(self.output.getNameLabel(self.node))
        self.post.set(self.output.getPostVar(self.node))


    def getLabel(self, event= None):
        """
        """
        t = PageText()

        self.check.begin(self.lab)
        self.stbar.busy()
        if len(self.label.get()) > 20 or len(self.label.get()) < 1:
            self.check.error(self.lab)
            self.stbar.set(t.ERROR_CAR)
        else:
            self.output.setLabelVar(self.node, self.label.get())

        self.stbar.idle()


    def getPost(self, event= None):
        """
        """
        self.output.setPostVar(self.node, self.post.get())


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


class OutputVarRayView(TkPage.Page):


    def _dependsPages(self, name):
        """
        Construction of the list of dependencies Pages.
        """
        self.case[name]['depends'] = ['models/therma', 'models/radiat']


    def _pageControl(self):
        """
        """
        self.info_turb_name = []


    def _createWidgets(self):
        """
        """
        t = PageText()

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

        f1 = Tix.Frame(lf1.frame, relief=FLAT)
        f1.pack(side=TOP, padx=10, pady=10)
        
        self.l1 = Tix.Label(f1, text=t.NAME, bd=1, relief=GROOVE)
        self.l2 = Tix.Label(f1, text=t.POST, bd=1, relief=GROOVE)
        self.l1.grid (row=0, column=0, ipadx=26, ipady=8)
        self.l2.grid (row=0, column=2, ipadx=10, ipady=1)

        self.f2 = Tix.ScrolledWindow(lf1.frame, relief=FLAT)
        self.f2.pack()


    def _initializeWidgets(self):
        """
        """
        dico = Tool.dicoRayLabel()
        print "dico", dico
        for nb in range(len(dico[0])):
            node = OutputVariableModel(self.case).getNodeVar(dico[0][nb])
            VariableOption(self.case, self.f2.window, self.stbar, 
                            self.balloon, dico[0][nb], node, 'black')


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


class PageText:
    """
    Storage of all texts and messages for this page.
    """
    def __init__(self):
        
        # 1) Texts
        #
        if Tool.GuiParam.lang == 'fr':
            self.ERROR_CAR    = "Le nombre de caractères doit etre compris"\
                                " entre 1 et 20"
            self.KEYWORD      = "Mot clé Code_Saturne: "
            self.NAME         = "Nom"
            self.POST         = "Post-\nprocessing"
            self.TITLE        = "Suivi des variables radiatives"
        else:
            self.ERROR_CAR    = "Number of character must be between 1 and 20"
            self.KEYWORD      = "Code_Saturne key word: "
            self.NAME         = "Name"
            self.POST         = "Post-\nprocessing"
            self.TITLE        = "Control Thermal Radiation"
        # 2) Messages
        #

        if Tool.GuiParam.lang == 'fr':
            self.MSG_POST      = "Suivi en Post-processing"
        else:
            self.MSG_POST      = "Post-processing"

#-------------------------------------------------------------------------------
# OutputVariableModel test case
#-------------------------------------------------------------------------------


class OutputVarRayTestCase(unittest.TestCase):
    """
    """
    def setUp(self):
        """
        This method is executed before all "check" methods.
        """
        from Base.XMLengine import Case, XMLDocument
        from Base.XMLinitialize import XMLinit
        Tool.GuiParam.lang = 'en'
        self.case = Case(None)
        XMLinit(self.case)
        self.doc = XMLDocument()


    def tearDown(self):
        """
        This method is executed after all "check" methods.
        """
        del self.case


    def checkOutputVarRayInstantiation(self):
        """
        Check whether the OutputVarRay Model class could be instantiated
        """
        model = None
        model = OutputVariableModel(self.case)
        assert model != None, 'Could not instantiate OutputVariableModel'


    def checkGetNodeVar(self):
        """
        """
        model = OutputVariableModel(self.case)
        import Pages.ThermalRadiation as ThRad
        rad = ThRad.ThermalRadiationModel(self.case)
        rad.mSetModel('dom')
        
        truc = model.getNodeVar('srad').toString()
        doc = '<property label="Srad" name="srad" status="on"/>'
        
        assert doc == truc,'Could not get node for variable'


    def checkSetandGetNameLabel(self):
        """
        """
        model = OutputVariableModel(self.case)
        import Pages.ThermalRadiation as ThRad
        rad = ThRad.ThermalRadiationModel(self.case)
        rad.mSetModel('dom')
        node = model.getNodeVar('wall_temp')
        model.setLabelVar(node,'temperature')

        assert model.getNameLabel(node) == 'temperature',\
        'Could not get label for node of variable'


    def checkSetandGetPostVar(self):
        """
        """
        model = OutputVariableModel(self.case)
        import Pages.ThermalRadiation as ThRad
        rad = ThRad.ThermalRadiationModel(self.case)
        rad.mSetModel('dom')
        node = model.getNodeVar('wall_temp')
        model.setPostVar(node,'off')
        
        assert model.getPostVar(node) == 'off',\
        'Could not set or get status for given node'


def suite():
    testSuite = unittest.makeSuite(OutputVarRayTestCase, "check")
    return testSuite

    
def runTest():
    print "OutputVarRayTestCase"
    runner = unittest.TextTestRunner()
    runner.run(suite())


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


syntax highlighted by Code2HTML, v. 0.9.1