# -*- 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 Page in which the user defines the path of the treated
case. The Page verify that the case configuration directories is appropriate.

This module contents the following classes:
- IdentityAndPathesModel
- IdentityAndPathesView
- PageText
"""


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

                  
import os, string
import Tix
from Tkconstants import *
import tkMessageBox


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


from Base.Common import *
import Base.Toolbox as Tool
import Base.XMLvariables as XMLvariables

import Base.Dialog as Dialog
import Base.TkPage as TkPage

import Pages.Matisse as Matisse
import Pages.MatisseType as MatisseType
import Pages.MatisseGeom as MatisseGeom


#-------------------------------------------------------------------------------
# Relevant directories label
#-------------------------------------------------------------------------------


sub_dir = ["DATA", "RESU", "FORT", "SCRIPTS"]
meshes_dir = "MAILLAGE"
unknown_dir = "????????"


#-------------------------------------------------------------------------------
# Model class
#-------------------------------------------------------------------------------


class IdentityAndPathesModel:
    """
    Class to manipulate xml file.
    """
    def __init__(self, case):
        """
        Constuctor.
        """
        self.case = case


    def getXmlFileName(self):
        """
        Get xml file'name
        """
        return self.case['xmlfile']

    def getCasePath(self):
        """
        Get xml file'name
        """
        return self.case['case_path']


    def setCaseandStudy(self, ncase, nstudy):
        """
        Put case and study's names
        """
        self.case.root().xmlSetAttribute(case=ncase, study=nstudy)



    def setCasePath(self, dircase):
        """
        Put path of case into xml file
        """
        self.case['case_path'] = dircase

    
    def setRelevantSubdir(self, val, dir):
        """
        Put relevant_subdir value into xml file
        """
        self.case['relevant_subdir'] = val 

        if self.case['relevant_subdir'] == 'yes' and \
           Tool.GuiParam.matisse and \
           dir == 'mesh_path':
            Matisse.MatisseInit(self.case)
            MatisseType.MatisseTypeModel(self.case).getMatisseType()
            MatisseGeom.MatisseGeomModel(self.case).updateMeshAndProbes()


    def setPathI(self, pathi, tag):
        """
        Put "relevant_subdir value into xml file
        """
        self.case[pathi] = tag


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


class IdentityAndPathesView(TkPage.Page):
    """
    Class to open Identity and Pathes Page.
    """
    def _dependsPages(self, name):
        """
        Construction of the list of dependencies Pages.
        """
        self.case[name]['depends'] = ['envirt/envelo',
                                      'managt/rstart',
                                      'managt/batch' ]

    def _tkControlVariables(self):
        """
        Tkinter variables declaration.
        """
        self.case_name = Tix.StringVar()
        self.case_path = Tix.StringVar()


    def _pageControl(self):
        """
        Xml node declaration and supplementary default value settings.
        """
        self.path = ['data_path',
                     'resu_path',
                     'user_src_path',
                     'scripts_path',
                     'mesh_path']

        self.mdl = IdentityAndPathesModel(self.case)


    def UpdateIdentityCase(self, case_path):
        """
        Update Study and Case names in the StudyId bar.
        """
        self.stbar.busy()

        case_name  = os.path.basename(case_path)
        self.spath = os.path.split(case_path)[0]
        study_name = os.path.basename(self.spath)

        self.mdl.setCaseandStudy(case_name, study_name)
        fic = self.mdl.getXmlFileName()
        self.study.set(study=study_name, case=case_name, file=fic)
    
        self.stbar.idle()


    def searchDir(self, event=None):
        """
        Open a File Dialog in order to search the case directory.
        """
        self.stbar.busy()

        t = PageText()
        path_case = self.mdl.getCasePath()
        dir_name = Dialog.dirselect(self.master,
                                    stbar=self.stbar,
                                    title=t.SELECT_DIR,
                                    default=path_case)
        if dir_name:
            self.case_path.set(dir_name)
            self.getAbsolutePath()
            self.UpdateIdentityCase(dir_name)

        self.stbar.idle()


    def getAbsolutePath(self, event=None):
        """
        Get absolute path for the case sub-directories and the meshes.
        """
        self.stbar.busy()
        t = PageText()

        case_dir = os.path.abspath(self.case_path.get())
        self.case_path.set(case_dir)
        self._scrollHandler(self.e1, "moveto", 1)

        if os.path.isdir(case_dir) :
            self.mdl.setCasePath(case_dir)
            self.UpdateIdentityCase(case_dir)
            self.stbar.clear()
            self.check2.begin(self.e1)

            msg = [t.MSG_DATA_PATH,
                   t.MSG_RESU_PATH,
                   t.MSG_SRC_PATH,
                   t.MSG_SCRIPTS_PATH]

            for i in range(0,4) :
                if sub_dir[i] in os.listdir(case_dir):
                    self.mdl.setPathI(self.path[i], os.path.abspath(case_dir + '/' + sub_dir[i]))
                    self.l2[i].config(text=sub_dir[i], bg=wm['identity'])
                    self.balloon.bind_widget(self.l2[i], statusmsg="")
                    self.mdl.setRelevantSubdir("yes", sub_dir[i])
                else:
                    self.mdl.setPathI(self.path[i], "")
                    self.l2[i].config(text=t.ERROR, bg=wm['selecterror'])
                    self.balloon.bind_widget(self.l2[i], statusmsg=msg[i])
                    self.mdl.setRelevantSubdir("no", sub_dir[i])
            
            if os.path.isdir(self.spath) and meshes_dir in os.listdir(self.spath):
                self.mdl.setPathI(self.path[4], os.path.abspath(self.spath + '/' + meshes_dir))
                self.l2[4].config(text=meshes_dir, bg=wm['identity'])
                self.balloon.bind_widget(self.l2[4], statusmsg="")
                self.mdl.setRelevantSubdir("yes", self.path[4])
            else:
                self.mdl.setPathI(self.path[4], "")
                self.l2[4].config(text=t.ERROR, bg=wm['selecterror'])
                self.balloon.bind_widget(self.l2[4], statusmsg=t.MSG_MESH_PATH)
                self.mdl.setRelevantSubdir("no", self.path[4])

        else:
            for i in range(0,5) :
                self.l2[i].config(text=unknown_dir, bg=wm['selecterror'])
            self.stbar.set(t.MSG_NO_PATH)
            self.check2.error(self.e1)
            self.mdl.setRelevantSubdir("no", '')

        self.stbar.idle()


    def doubleClick(self, event=None):
        """
        """
        self.e1.selection_range(0,END)


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

        # FIRST PART : CASE PATH
        #
        lf1 = Tix.LabelFrame(self.myPage, label=t.MAIN_DIRECTORY, relief=FLAT)
        lf1.label.config(font=fT)
        lf1.pack(side=TOP, fill=X, padx=10, pady=10)

        top = Tix.Frame(lf1.frame, relief=FLAT)
        top.pack(side=TOP, pady=15)

        self.e1 = Tix.Entry(top, width=40, textvariable=self.case_path)
        self.e1.grid(row=0, column=0, padx=3)
        self.balloon.bind_widget(self.e1, statusmsg=t.MSG_CASE_PATH)

        scroll = Tix.Scrollbar(top, orient=HORIZONTAL, width=10, bd=2,
                               command=TkPage.Callback(self._scrollHandler, self.e1))
        scroll.grid(row=1, column=0, sticky=E+W, padx=3)
        self.e1['xscrollcommand'] = scroll.set
        self.e1.event_add("<<E>>", "<Return>", "<Leave>", "<FocusOut>")
        self.e1.bind("<<E>>", self.getAbsolutePath)
        self.e1.bind("<Shift-Motion>", lambda event=None, w=self.e1: w.selection_range(0,END))

        # Search directory in list
        #
        self.img = Tix.PhotoImage(file=PIC_PATH+'rubic1c.gif')
        b1 = Tix.Button(top, image=self.img, command=self.searchDir)
        b1.grid(row=0, column=1, rowspan=2, padx=3)
        self.balloon.bind_widget(b1, balloonmsg=t.MSG_CASE_DIR)

        # SECOND PART : SUBDIRECTORIES
        #
        lf2 = Tix.LabelFrame(self.myPage, label=t.SUBDIRECTORIES, relief=FLAT)
        lf2.label.config(font=fT)
        lf2.pack(side=TOP, fill=X, padx=10, pady=10, ipady=15)

        self.l2    = [0]*5

        for (num, txt, msg) in [(0, t.DATA,      t.MSG_DATA_PATH    ),
                                (1, t.RESU,      t.MSG_RESU_PATH    ),
                                (2, t.USER_SRC,  t.MSG_SRC_PATH     ),
                                (3, t.SCRIPTS,   t.MSG_SCRIPTS_PATH ),
                                (4, t.MESH_PATH, t.MSG_MESH_PATH    )]:

            Tix.Label(lf2.frame, text=txt).grid(row=num, column=0, padx=3, pady=3, sticky=W)

            self.l2[num] = Tix.Label(lf2.frame, bg=wm['identity'], bd=2, relief=GROOVE)
            self.l2[num].grid(row=num, column=1, ipadx=3, padx=3, pady=3, sticky=W)


    def _initializeWidgets(self):
        """
        Initialize the conte ns of the widgets.
        """
        t = PageText()

        if not self.case['case_path']:

            # Set case path to its default value
            #
            fic = self.mdl.getXmlFileName()
            if not fic:
                f = os.getcwd()
                if os.path.basename(f) == 'DATA': f = os.path.dirname(f)
                self.mdl.setCasePath(f)
            else :
                file_dir = os.path.split(fic)[0]
                if file_dir:
                    self.mdl.setCasePath(os.path.split(file_dir)[0])
                    if not os.path.basename(file_dir) == 'DATA':
                        Dialog.Warning(self.master, text=t.MSG_NO_DATA)
                        self.mdl.setCasePath(file_dir)
                else:
                    self.mdl.setCasePath(os.path.split(os.getcwd())[0])

        self.case_path.set(self.mdl.getCasePath())
        self.getAbsolutePath()


#-------------------------------------------------------------------------------
# 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.CASE_NAME       = "Nom du cas :"
            self.DATA            = "Données"
            self.MAIN_DIRECTORY  = "Répertoire du cas"
            self.MESH_PATH       = "Répertoires des maillages"
            self.PATH_UNKNOWN    = "Les répertoires suivants n'ont "\
                                   "pas pu être renseignés automatiquement :\n\n"
            self.RESU            = "Résultats"
            self.SCRIPTS         = "Scripts d'exécution"
            self.SUBDIRECTORIES  = "Sous-répertoires associés au cas"
            self.USER_SRC        = "Sous-programmes utilisateurs"
            self.WARNING         = "Attention"
            self.ERROR           = "Sous-répertoire associé inexistant"
            self.SELECT_DIR      = "Sélectionnez un répertoire"
        else:
            self.CASE_NAME       = "Name of the case:"
            self.DATA            = "Data"
            self.MAIN_DIRECTORY  = "Directory of the case"
            self.MESH_PATH       = "Directory of meshes"
            self.PATH_UNKNOWN    = "The following paths could not be "\
                                   "found automatically:\n\n"
            self.RESU            = "Results"
            self.SCRIPTS         = "Running scripts"
            self.SUBDIRECTORIES  = "Associated sub-directories of the case"
            self.USER_SRC        = "Users subroutines"
            self.WARNING         = "Warning"
            self.ERROR           = "Associated sub-directory not found"
            self.SELECT_DIR      = "Select directory"

        # 2) Messages
        #
        if Tool.GuiParam.lang == 'fr':
            self.MSG_CASE_DIR      = "Sélectionner le répertoire du cas"
            self.MSG_CASE_PATH     = "Donnez le chemin absolu du répertoire du "\
                                     "cas ou utilisez la boite de dialogue."
            self.MSG_DATA_PATH     = "Attention : la présence du sous-répertoire "\
                                     "DATA est obligatoire."
            self.MSG_MESH_PATH     = "Attention : la présence du répertoire "\
                                     "MAILLAGE est obligatoire et doit être au "\
                                     "même niveau que celui du réperoire du cas."
            self.MSG_RESU_PATH     = "Attention : la présence du sous-répertoire "\
                                     "RESU est obligatoire."
            self.MSG_SCRIPTS_PATH  = "Attention : la présence du sous-répertoire "\
                                     "SCRIPTS est obligatoire."
            self.MSG_SRC_PATH      = "Attention : la présence du sous-répertoire "\
                                     "FORT est obligatoire."
            self.MSG_NO_PATH       = "Attention : le répertoire donné n'existe pas."
            self.MSG_NO_DATA       = "Attention : le fichier xml devrait être dans "\
                                     "le répertoire DATA du cas."
        else:
            self.MSG_CASE_DIR      = "Select the case directory"
            self.MSG_CASE_PATH     = "Please give the absolute path of the case "\
                                     "directory or use the dialog box."
            self.MSG_DATA_PATH     = "Warning: the sub-directory DATA existence "\
                                     "is required."
            self.MSG_MESH_PATH     = "Warning: the directory MAILLAGE existence "\
                                     "is required, at the level of the case directory."
            self.MSG_RESU_PATH     = "Warning: the sub-directory RESU existence "\
                                     "is required."
            self.MSG_SCRIPTS_PATH  = "Warning: the sub-directory SCRIPTS existence "\
                                     "is required."
            self.MSG_SRC_PATH      = "Warning: the sub-directory FORT existence "\
                                     "is required."
            self.MSG_NO_PATH       = "Warning: the given directory does not exist."
            self.MSG_NO_DATA       = "Warning: the xml file must be in directory "\
                                     "DATA of the case."


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


syntax highlighted by Code2HTML, v. 0.9.1