# -*- coding: iso-8859-1 -*-

# ==============================================================================
# COPYRIGHT (C) 1991 - 2003  EDF R&D                  WWW.CODE-ASTER.ORG
# THIS PROGRAM 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.
#
# THIS PROGRAM 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 THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER,
#    1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE.
# ==============================================================================

"""Definition of ASTER_CONFIG class.
"""

__revision__ = "$Id: as_config.py 2646 2006-12-19 13:31:52Z courtois $"


# ----- differ messages translation
def _(mesg):
   return mesg

import os
import re

from utils     import get_absolute_dirname

#-------------------------------------------------------------------------------
#-------------------------------------------------------------------------------
#-------------------------------------------------------------------------------
class ASTER_CONFIG:
   """Class to read a configuration file of a Code_Aster version ('config.txt')
   and give easy access to the parameters.
   """
#-------------------------------------------------------------------------------
   def __init__(self, config_file, run=None):
      """config_file : filename of the 'config.txt' file to read
      run   : ASTER_RUN object (optional)
      """
      # ----- initialisations
      self.config = {}
      self.filename = config_file
      self.dirn = get_absolute_dirname(config_file)
      self.verbose = False
      self.debug = False
      aster_root = '/opt/aster'

      # ----- reference to ASTER_RUN object which manages the execution
      self.run = run
      if run != None:
         self.verbose = run['verbose']
         self.debug = run['debug']
         aster_root = run.aster_root

      # ----- set optionnal/defaults values (ALWAYS AS LIST !)
      # keep 'Eficas' by default (instead of 'Python') to support older version
      reppy = 'Eficas'
      self.config = {
         # name of source directories
         'SRCFOR'          : ['bibfor'],
         'SRCFERM'         : ['fermetur'],
         'SRCC'            : ['bibc'],
         'SRCPY'           : ['bibpyt'],
         'SRCCATA'         : ['catalo'],
         'SRCCAPY'         : ['catapy'],
         'SRCTEST'         : ['astest'],
         'SRCMAT'          : ['materiau'],
         'SRCHIST'         : ['histor'],
         # name of "binaries" (as results of a make)
         'MAKE'            : ['debug nodebug'],
         'BIN_NODBG'       : ['asteru.exe'],
         'BIN_DBG'         : ['asterd.exe'],
         'BINCMDE'         : ['commande'],
         'BINELE'          : ['elements'],
         'BINPICKLED'      : ['cata_ele.pickled'],
         'BINLIB_NODBG'    : ['lib_obj/lib_aster.lib'], # new values are
         'BINLIB_DBG'      : ['lib_dbg/lib_aster.lib'], #     lib/libaster.a and libasterd.a
         'BINLIBF_NODBG'   : ['lib_obj/ferm.lib'],      # and lib/libferm.a  and libfermd.a
         'BINLIBF_DBG'     : ['lib_dbg/ferm.lib'],
         'BINOBJ_NODBG'    : ['obj'],
         'BINOBJF_NODBG'   : ['obj_f'],
         'BINOBJ_DBG'      : ['dbg'],
         'BINOBJF_DBG'     : ['dbg_f'],
         'BINOBJ_MAIN'     : ['python.o'],
         # name of bibpyt in execution directory
         'REPPY'           : [reppy],
         # modules to compile elements
         'MAKE_SURCH_OFFI' : [os.path.join('Lecture_Cata_Ele', 'make_surch_offi.py')],
         'MAKE_CAPY_OFFI'  : [os.path.join('Lecture_Cata_Ele', 'make_capy_offi.py')],
         # command line arguments for aster executable
         'REPOUT'          : [os.path.join(aster_root, 'outils')],
         'REPMAT'          : [os.path.join(self.dirn, 'materiau')],
         'REPDEX'          : [os.path.join(self.dirn, 'datg')],
         'ARGPYT'          : [os.path.join('Execution', 'E_SUPERV.py')],
         'ARGEXE'          : ['-eficas_path '+reppy],
      }
      
      # ----- read config file
      if not os.path.isfile(config_file):
         self._mess(_('file not found : %s') % config_file, _('<F>_FILE_NOT_FOUND'))

      f = open(config_file, 'r')
      content = f.read()
      f.close()
      self.config.update(self._parse(content))
      
      if self.debug:
         print '<DBG> <init> ASTER_CONFIG :'
         print self

#-------------------------------------------------------------------------------
   def __repr__(self):
      """Pretty print configuration
      """
      fmt = ' %-10s = %s'
      txt = []
      txt.append(fmt % ('Filename', self.filename))
      sorted_keys = self.config.keys()
      sorted_keys.sort()
      for key in sorted_keys:
         txt.append(fmt % (key, self.config[key]))
      return os.linesep.join(txt)

#-------------------------------------------------------------------------------
   def __getitem__(self, key):
      """Return the value of parameter 'key', or '' if not exists
      (so never raise KeyError exception).
      """
      if self.config.has_key(key):
         return self.config[key]
      else:
         return ['']

#-------------------------------------------------------------------------------
   def get_with_absolute_path(self, key, sep=' '):
      """For fields containing pathnames returns absolute path names.
      """
      l_res = []
      for val in self[key]:
         l_res.extend([os.path.join(self.dirn, path) for path in val.split()])
      return l_res

#-------------------------------------------------------------------------------
   def _mess(self, msg, cod='', store=False):
      """Just print a message
      """
      if hasattr(self.run, 'Mess'):
         self.run.Mess(msg, cod, store)
      else:
         print '%-18s %s' % (cod, msg)

#-------------------------------------------------------------------------------
   def _parse(self, content):
      """Extract fields of config from 'content'
      """
      cfg = {}
      self.content = content
      for l in content.split(os.linesep):
         if not re.search('^[ ]*#', l):
            try:
               typ, nam, ver, val = l.split('|')
               #print '========>', typ, '//', nam, '//', ver, '//', val
               typ = re.sub('^[ ]*', '', re.sub('[ ]*$', '', typ))
               val = re.sub('^[ ]*', '', re.sub('[ ]*$', '', val))
               if val != '':
                  if cfg.has_key(typ):
                     cfg[typ].append(val)
                  else:
                     cfg[typ] = [val]
            except ValueError:
               pass
      return cfg

