#########################################################################
# COPYRIGHT (C) 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.        #
#########################################################################

# $Id: meshtool.tcl 2288 2006-10-13 12:36:38Z courtois $

# retourne le format associé à un type de maillage ou l'extension
#################################################################
proc type2format { typ ext } {
   global meshtool_format meshtool_type
   set trouv 0
   for { set i 0 } { $i < [llength $meshtool_type] } { incr i } {
      if { $typ == [lindex $meshtool_type $i] || $ext == ".[lindex $meshtool_type $i]" \
        || $ext == ".[lindex $meshtool_format $i]" } {
         set trouv 1
         return [lindex $meshtool_format $i]
      }
   }
   return ""
}

# extension à partir du format
#################################################################
proc format2ext { fmt } {
   global meshtool_format meshtool_type
   set trouv 0
   for { set i 0 } { $i < [llength $meshtool_format] } { incr i } {
      if { $fmt == [lindex $meshtool_format $i] } {
         set trouv 1
         return ".[lindex $meshtool_type $i]"
      }
   }
   return ".convert"
}

# positionne le nom du maillage résultat
#################################################################
proc auto_mesh_out { } {
   global meshtool_para
   
   set root $meshtool_para(mesh_in)
   
   set ext [file extension $root]
   # retirer .gz
   if { $ext == ".gz" } {
      set root [file rootname $root]
   }
   # retirer l'extension initial
   if { [file extension $root] == [format2ext $meshtool_para(format_in)] \
     || [file extension $root] == ".$meshtool_para(format_in)" } {
      set root [file rootname $root]
   }
   
   append root [format2ext $meshtool_para(format_out)]
   set meshtool_para(mesh_out) $root

   if { $meshtool_para(compress_result) == 1 } {
      append meshtool_para(mesh_out) ".gz"
   }
}

# Vérifie que les données nécessaires sont présentes
# puis appel le service "as_exec_special"
# numfich pour compatibilité avec les run_$outil
#################################################################
proc run_MeshTool { {numfich -1} } {
   global meshtool_para meshtool_format meshtool_type
   set meshtool_format {aster med  gmsh ideas gibi}
   set meshtool_type   {mail  mmed msh  msup  mgib}
   
   # fichier IN sélectionné
   set lfich $astk::sel(filename)
   if { [llength $lfich] != 1 } {
      return 50
   }
   set indice $astk::sel(indice)
   set var $astk::sel(liste)
   set typ $astk::profil($var,fich,$indice,type)
   set nom [abspath $var $astk::profil($var,fich,$indice,nom)]
   
   set ext [file extension $nom]
   if { $ext == ".gz" } {
      set root [file rootname $nom]
      set ext [file extension $root]
   }

   set meshtool_para(format_in)       [type2format $typ $ext]
   set meshtool_para(mesh_in)         $nom
   set meshtool_para(format_out)      "med"
   set meshtool_para(compress_result) 0
   auto_mesh_out
   set meshtool_para(info_mail)       1
   set meshtool_para(info_cmd)        1
#   set meshtool_para(visu)       "1"
   if { $astk::config(-1,langue) == "FR" } {
      set meshtool_para(lang)       "FRANCAIS"
   } else {
      set meshtool_para(lang)       "ENGLISH"
   }
   
   # appel la boite de dialogue
   set iret [meshtool_ihm]
   if { $iret != 0 } {
      # annulé
      return 0
   }
   set fout [abspath $var $meshtool_para(mesh_out)]
   
   # on met les lignes du .export sauf les unités logiques
   # qui seront choisies par meshtool (pour n'être qu'à un seul endroit)
   set astk::profil(special) "meshtool%NEXT%"

   # chemin des fichiers de maillage IN et OUT
   set valf ""
   set valout ""
   set sfic $astk::inv(serv,$astk::profil($var,fich,$indice,serv))
   set serv $astk::inv(serv,$astk::profil(serveur))
   if { [ashare::meme_machine $astk::config($sfic,nom_complet) $astk::config($serv,nom_complet)] != 1
     || $astk::config($sfic,login) != $astk::config($serv,login) } {
      append valf   "$astk::config($sfic,login)@$astk::config($sfic,nom_complet):"
      append valout "$astk::config($sfic,login)@$astk::config($sfic,nom_complet):"
   }
   append valf   $nom
   append valout $fout
   # enlever les /./
   regsub -all {/\./} $valf   "/" valf
   regsub -all {/\./} $valout "/" valout

   set flagIN " D"
   if { $astk::profil($var,fich,$indice,compress) } {
      append flagIN "C"
   }
   set flagOUT " R"
   if { $meshtool_para(compress_result) == 1 } {
      append flagOUT "C"
   }
   
   # remplit special
   append astk::profil(special) "F libr $valf $flagIN"
   append astk::profil(special) "%NEXT%"
   append astk::profil(special) "F libr $valout $flagOUT"
   
   # paramètres décodés par le service "as_exec_special"
   # ATTENTION : syntaxe Python, "'" autour des chaines
   append astk::profil(special) "%NEXT%format_in='$meshtool_para(format_in)'"
   append astk::profil(special) "%NEXT%format_out='$meshtool_para(format_out)'"
   append astk::profil(special) "%NEXT%info_mail=$meshtool_para(info_mail)"
   append astk::profil(special) "%NEXT%info_cmd=$meshtool_para(info_cmd)"
#   append astk::profil(special) "%NEXT%visu=$meshtool_para(visu)"
   append astk::profil(special) "%NEXT%lang='$meshtool_para(lang)'"
   
   if { $ashare::dbg >= 4 } {
      ashare::log "<DEBUG> (run_MeshTool) special : $astk::profil(special)"
   }
# on force le suivi interactif
   set astk::profil(suivi_interactif) 1
# enregistrement du profil
   set iret [enregistrer $astk::profil(serv_profil) $astk::profil(nom_profil)]
   if { $iret != 0 } {
      return 5
   }
# indices ihm
   set serv $astk::inv(serv,$astk::profil(serveur))
# nom du fichier export
   set serv_export $astk::profil(serv_profil)
   set nom_export [file rootname $astk::profil(nom_profil)]
   append nom_export "_mesh.export"
# export du profil sans les vérifications supplémentaires
   set iret [exporter astk_serv $serv_export $nom_export "noverif" "non"]
   if { $iret == 4 } {
      return $iret
   } elseif { $iret == 2 } {
   # alarmes emises
      change_status [ashare::mess info 16]
      tk_messageBox -message [ashare::mess info 16] -type ok -icon info
   }
   set astk::profil(special) ""

# préparation de la ligne de commande à exécuter
   set lcmd ""
   set argu ""
# profil
   append lcmd [file join $astk::config($serv,rep_serv) as_serv]
   append lcmd " as_exec_special"
   append lcmd " --remote_shell_protocol $astk::config(-1,remote_shell_protocol)"
   append lcmd " --remote_copy_protocol $astk::config(-1,remote_copy_protocol)"
   if { [ashare::meme_machine $astk::config($serv,nom_complet) $astk::config($serv_export,nom_complet)] != 1
     || $astk::config($serv,login) != $astk::config($serv_export,login) } {
      append argu "$astk::config($serv_export,login)@$astk::config($serv_export,nom_complet):"
   }
   append argu $nom_export

#  execution
   set iret [ ashare::rexec_cmd $serv astk::config $lcmd $argu 0 out .]
   set jret $iret
   if { $iret == 0 } {
   # ajouter le maillage résultat dans le profil si pas déjà présent
      set trouv 0
      for { set i 0 } {$i < $astk::profil($var,nbfic)} {incr i} {
         if { [abspath $var $fout] == [abspath $var $astk::profil($var,fich,$i,nom)] } {
            set trouv 1
         }
      }
      if { $trouv == 0 } {
         $astk::ihm(fenetre).active.princ.icone.nouveau invoke
         set i [expr $astk::profil($var,nbfic) - 1]
         
         set ext [format2ext $meshtool_para(format_out)]
         regsub "^." $ext "" typ
         
         set astk::profil($var,fich,$i,nom)  [relpath $var $fout]
         set astk::profil($var,fich,$i,type) $typ
         set astk::profil($var,fich,$i,FR)   "F"
         set nul 0
         set ilibr 0
         for {set j 0} {$j < $astk::UL($var,nbre)} {incr j} {
            if { $typ == $astk::UL($var,$j,nom) } {
               set nul $j
            }
            if { $astk::UL($var,$j,nom) == "libr" } {
               set ilibr $j
            }
         }
         if { $nul == 0 } {
            set nul $ilibr
         }
         # ne doit pas être pris en compte dans l'export
         set astk::profil($var,fich,$i,donnee)   0
         set astk::profil($var,fich,$i,resultat) 0
         set astk::profil($var,fich,$i,compress) $meshtool_para(compress_result)
         set_UL $i $nul $var
      }
   
   # traitement du retour
      set nomjob [get_nomjob]
      append nomjob "_mesh"
      set jret [retour_as_exec $nomjob $out]
#      tk_messageBox -message $msg -type ok -icon info
      show_fen $astk::ihm(asjob)
   
   } else {
   # pb lancement
      ashare::mess "erreur" 3 $lcmd $jret $out
      return "MeshTool"
   }
   if { $ashare::dbg >= 4 } {
      ashare::log "<DEBUG> (run_MeshTool) iret : $iret, output :\n$out"
      catch { ashare::log "<DEBUG> (run_MeshTool) jobid=$jobid\nqueue=$queue" }
   }
   
   return $jret
}



# fenêtre pour renseigner les paramètres de meshtool
# retourne 0 si ok, 1 si annuler
#################################################################
proc meshtool_ihm { } {
   global iret_meshtool meshtool_para meshtool_format
   
   set iret_meshtool 0

   set fen .f_meshtool
   catch {destroy $fen}
   set tit [ashare::mess ihm 369]
   toplevel $fen
   wm title $fen $tit
   wm transient $fen .

   set marg1 10
   set marg2 5

#  Maillage en données
   pack [frame $fen.f1 -relief sunken -bd 1] -fill x -anchor nw -padx $marg1 -pady $marg1
      pack [frame $fen.f1.nom -bd 0] -side top -fill x -padx $marg2 -pady $marg2
      pack [frame $fen.f1.fmt -bd 0] -side top -fill x -padx $marg2 -pady $marg2

   label $fen.f1.nom.lbl -font $astk::ihm(font,lab) -text [ashare::mess ihm 274] -width 20 -anchor w
   entry $fen.f1.nom.path -width 50 -font $astk::ihm(font,val) -textvariable meshtool_para(mesh_in) \
      -state disabled
   pack $fen.f1.nom.lbl $fen.f1.nom.path -pady 3 -side left

   label $fen.f1.fmt.lbl -font $astk::ihm(font,lab) -text [ashare::mess ihm 339] -width 20 -anchor w
   pack $fen.f1.fmt.lbl -side left
   for {set i 0} {$i < [llength $meshtool_format]} {incr i} {
      set lab [lindex $meshtool_format $i]
      radiobutton $fen.f1.fmt.$lab -font $astk::ihm(font,lab) -text $lab -value $lab \
         -variable meshtool_para(format_in)
      pack $fen.f1.fmt.$lab -side left
   }

#  Maillage résultat
   pack [frame $fen.f2 -relief sunken -bd 1] -fill x -anchor nw -padx $marg1 -pady $marg1
      pack [frame $fen.f2.nom -bd 0] -side top -fill x -padx $marg2 -pady $marg2
      pack [frame $fen.f2.fmt -bd 0] -side top -fill x -padx $marg2 -pady $marg2

   label $fen.f2.nom.lbl -font $astk::ihm(font,lab) -text [ashare::mess ihm 311] -width 20 -anchor w
   entry $fen.f2.nom.path -width 50 -font $astk::ihm(font,val) -textvariable meshtool_para(mesh_out)
   pack $fen.f2.nom.lbl $fen.f2.nom.path -pady 3 -side left

   label $fen.f2.fmt.lbl -font $astk::ihm(font,lab) -text [ashare::mess ihm 339] -width 20 -anchor w
   pack $fen.f2.fmt.lbl -side left
   for {set i 0} {$i < [llength $meshtool_format]} {incr i} {
      set lab [lindex $meshtool_format $i]
      radiobutton $fen.f2.fmt.$lab -font $astk::ihm(font,lab) -text $lab -value $lab \
         -variable meshtool_para(format_out) -command auto_mesh_out
      pack $fen.f2.fmt.$lab -side left
   }

# paramètres
   pack [frame $fen.f3 -relief sunken -bd 1] -fill x -anchor n -padx $marg1 -pady $marg1
   label $fen.f3.lbl -font $astk::ihm(font,lab) -text [ashare::mess ihm 69] -width 20 -anchor w
   pack $fen.f3.lbl -side left -fill x -anchor nw
      pack [frame $fen.f3.infma -bd 0] -fill x -side top -padx $marg2 -pady $marg2
      checkbutton $fen.f3.infma.cb -variable meshtool_para(info_mail) -onvalue 1 -offvalue 0 \
         -anchor w -text [ashare::mess ihm 338]
      pack $fen.f3.infma.cb  -side left
      
      pack [frame $fen.f3.infcmd -bd 0] -fill x -side top -padx $marg2 -pady $marg2
      checkbutton $fen.f3.infcmd.cb -variable meshtool_para(info_cmd) -onvalue 2 -offvalue 1 \
         -anchor w -text [ashare::mess ihm 336]
      pack $fen.f3.infcmd.cb -side left
      
      pack [frame $fen.f3.cmpr -bd 0] -fill x -side top -padx $marg2 -pady $marg2
      checkbutton $fen.f3.cmpr.cb -variable meshtool_para(compress_result) -onvalue 1 -offvalue 0 \
         -anchor w -text [ashare::mess ihm 86] -command auto_mesh_out
      pack $fen.f3.cmpr.cb -side left
      
#      pack [frame $fen.f3.visu -bd 0] -fill x -side top -padx $marg2 -pady $marg2
#      checkbutton $fen.f3.visu.cb -variable meshtool_para(visu) -onvalue 2 -offvalue 1 \
#         -anchor w -text [ashare::mess ihm 97]
#      pack $fen.f3.visu.cb   -side left

#  fermer
   pack [frame $fen.valid -relief solid -bd 0] -padx $marg1 -pady $marg1
   button $fen.valid.ok -font $astk::ihm(font,labbout) -text "Ok" \
      -background $astk::ihm(couleur,valid) \
      -command "valid_para $fen"
   button $fen.valid.can -font $astk::ihm(font,labbout) -text [ashare::mess ihm 85] \
      -background $astk::ihm(couleur,annul) \
      -command "set iret_meshtool 1 ; destroy $fen"
   pack $fen.valid.ok $fen.valid.can -side left -padx 10 -pady 3
   focus $fen.f2.nom.path

   tkwait window $fen
   return $iret_meshtool
}

# valide les valeurs des paramètres
#################################################################
proc valid_para { parent } {
   global iret_meshtool meshtool_format meshtool_para
   if { [lsearch $meshtool_format $meshtool_para(format_in)] < 0 } {
      set msg [ashare::mess ihm 97]
      change_status $msg
      tk_messageBox -message $msg -type ok -icon error -parent $parent
      return
   }
   
   destroy $parent
}
