/*
Copyright Renaud GICQUEL 2005-2011  
renaud.gicquel@s4e2.com

Ce logiciel est un programme informatique servant à modéliser des systèmes énergétiques.   

Ce logiciel est régi par la licence CeCILL soumise au droit français et respectant les principes de diffusion des logiciels libres. Vous pouvez utiliser, modifier et/ou redistribuer ce programme sous les conditions de la licence CeCILL telle que diffusée par le CEA, le CNRS et l'INRIA  sur le site "http://www.cecill.info".  

En contrepartie de l'accessibilité au code source et des droits de copie, de modification et de redistribution accordés par cette licence, il n'est offert aux utilisateurs qu'une garantie limitée.  Pour les mêmes raisons, seule une responsabilité restreinte pèse sur l'auteur du programme,  le titulaire des droits patrimoniaux et les concédants successifs.  

A cet égard  l'attention de l'utilisateur est attirée sur les risques associés au chargement,  à l'utilisation,  à la modification et/ou au développement et à la reproduction du logiciel par l'utilisateur étant  donné sa spécificité de logiciel libre, qui peut le rendre complexe à  manipuler et qui le réserve donc à des développeurs et des professionnels avertis possédant  des  connaissances  informatiques approfondies.  Les utilisateurs sont donc invités à charger  et  tester  l'adéquation  du logiciel à leurs besoins dans des conditions permettant d'assurer la sécurité de leurs systèmes et ou de leurs données et, plus généralement,  à l'utiliser et l'exploiter dans les mêmes conditions de sécurité.   

Le fait que vous puissiez accéder à cet en-tête signifie que vous avez  pris connaissance de la licence CeCILL, et que vous en avez accepté les termes. 

This software is a computer program whose purpose is to model energy systems.  

This software is governed by the CeCILL  license under French law and abiding by the rules of distribution of free software.  You can  use,  modify and/ or redistribute the software under the terms of the CeCILL license as circulated by CEA, CNRS and INRIA at the following URL "http://www.cecill.info".   

As a counterpart to the access to the source code and  rights to copy, modify and redistribute granted by the license, users are provided only with a limited warranty  and the software's author,  the holder of the economic rights,  and the successive licensors  have only  limited liability.   

In this respect, the user's attention is drawn to the risks associated with loading,  using,  modifying and/or developing or reproducing the software by the user in light of its specific status of free software, that may mean  that it is complicated to manipulate,  and  that  also therefore means  that it is reserved for developers  and  experienced professionals having in-depth computer knowledge. Users are therefore encouraged to load and test the software's suitability as regards their requirements in conditions enabling the security of their systems and/or  data to be ensured and,  more generally, to use and operate it in the  same conditions as regards security.   

The fact that you are presently reading this means that you have had knowledge of the CeCILL license and that you accept its terms.  
*/
package pilot;

import javax.swing.*;
import java.beans.*;
import java.awt.*;
import java.io.*;
import rg.corps.*;
import rg.thopt.*;
import java.util.*;
import extThopt.*;

public class Pilot extends javax.swing.JFrame{
    
    ProjetThopt proj;
    
 //   extThopt.Thrust thrust;
	public Pilot()
	{
		//{{INIT_CONTROLS
		getContentPane().setLayout(null);
		setSize(539,300);
		setVisible(false);
		JPanel1.setLayout(null);
		getContentPane().add(JPanel1);
		JPanel1.setBounds(0,0,500,360);
		bCancel.setText("Quitter");
		bCancel.setActionCommand("Quit");
		JPanel1.add(bCancel);
		bCancel.setBounds(324,150,84,36);
		bOK.setText("Run Thermoptim and load  example");
		bOK.setActionCommand("OK");
	//	JPanel1.add(bOK);
		bOK.setBounds(24,12,264,36);
		bRecalcThopt.setText("Lancer Thermoptim");
		JPanel1.add(bRecalcThopt);
		bRecalcThopt.setBounds(36,150,216,36);
		setTitle("Lanceur Thermoptim sous Eclipse");
		instruct.setBounds(30,0,470,130);
		JPanel1.add(instruct);
		instruct.setFont(new Font("Monospaced",Font.BOLD+Font.ITALIC,12));
		instruct.setText("Cette fenêtre vous permet de lancer Thermoptim.\n"
				+ "Vous pouvez ouvrir un navigateur pour visualiser les explorations dirigées :\n"
				+"- soit en local dans le répertoire Nav_Thopt\\explorations\\ctc\n"
				+"- soit en ligne à cette adresse : https://ctc.mines-paristech.fr/ed/accueilEnLigne.html");
		instruct.setEditable(false);
		//.setAutoscrolls(true);
		//}}

		//{{REGISTER_LISTENERS
		SymWindow aSymWindow = new SymWindow();
		this.addWindowListener(aSymWindow);
		SymMouse aSymMouse = new SymMouse();
		SymAction lSymAction = new SymAction();
		bOK.addActionListener(lSymAction);
		bCancel.addActionListener(lSymAction);
		SymItem lSymItem = new SymItem();
		bRecalcThopt.addActionListener(lSymAction);
		//}}

		//{{INIT_MENUS
		//}}
        init();
	}

	public Pilot(String title)
	{
		this();
		setTitle(title);
	}
	public void setVisible(boolean b)
	{
		if(b)
		{
			setLocation(50, 50);
		}
	super.setVisible(b);
	}


	public void addNotify()
	{
		// Record the size of the window prior to calling parents addNotify.
		Dimension d = getSize();

		super.addNotify();

		if (fComponentsAdjusted)
			return;

		// Adjust components according to the insets
		Insets ins = getInsets();
		setSize(ins.left + ins.right + d.width, ins.top + ins.bottom + d.height);
		Component components[] = getContentPane().getComponents();
		for (int i = 0; i < components.length; i++)
			{
			Point p = components[i].getLocation();
			p.translate(ins.left, ins.top);
			components[i].setLocation(p);
		}
		fComponentsAdjusted = true;
	}

	// Used for addNotify check.
	boolean fComponentsAdjusted = false;

	class SymWindow extends java.awt.event.WindowAdapter
	{
		public void windowClosing(java.awt.event.WindowEvent event)
		{
		Object object = event.getSource();
		if (object == Pilot.this)
			TuteurGest_WindowClosing(event);
		}
	}

	void TuteurGest_WindowClosing(java.awt.event.WindowEvent event)
	{
		System.exit(0);		 // dispose of the Frame.
	}
	//{{DECLARE_CONTROLS
	javax.swing.JPanel JPanel1 = new javax.swing.JPanel();
	javax.swing.JButton bCancel = new javax.swing.JButton();
	javax.swing.JButton bOK = new javax.swing.JButton();
	javax.swing.JButton bRecalcThopt = new javax.swing.JButton();
	javax.swing.JTextPane  instruct = new javax.swing.JTextPane ();
//	javax.swing.JLabel instruct = new javax.swing.JLabel();
	//}}

	//{{DECLARE_MENUS
	//}}


	class SymMouse extends java.awt.event.MouseAdapter
	{
		public void mousePressed(java.awt.event.MouseEvent event)
		{
		}
	}
	
	private void init(){
	}

	class SymAction implements java.awt.event.ActionListener
	{
		public void actionPerformed(java.awt.event.ActionEvent event)
		{
			Object object = event.getSource();
			if (object == bOK)
				bOK_actionPerformed(event);
			else if (object == bCancel)
				bCancel_actionPerformed(event);
			else if (object == bRecalcThopt)
				bRecalcThopt_actionPerformed(event);
		}
	}

	void bOK_actionPerformed(java.awt.event.ActionEvent event)
	{
	    try{
	        runThopt();
	        loadProject();
	   //     listProcesses();
	   //     printProperties();
	   //     recalcProperties();
	    }
        catch(Exception ioexception){
            ioexception.printStackTrace();
        }
	}

	/**
	* Lance l'exécution de Thermoptim
    *<p>
	* Runs Thermoptim
	*/
	public void runThopt(){
	    if(proj==null)proj=new ProjetThopt();
	    proj.setVisible(true);
	//    proj.setupThopt();
	    proj.openEditor();
	}

	/**
	* Charge un projet et un schéma
    *<p>
	* Loads a project and a diagram
	*/
	public void loadProject(){
	    String[] args=new String[4];
	    args[0]="monCapteur.prj";//project file name
	    args[1]="monCapteur.dia";//diagram file name
	    
	    
        args[2]=".";//working directory
	    args[3]="noTest";//working directory  
	    proj.loadSelection(args);
	}
	
	/**
	* Liste les transfos du projet chargé
    *<p>
	* Lists the processes of the project loaded
	*/
	 public void listProcesses(){
	    String[] list=proj.getProcessList();
	    for (int i=0;i<list.length;i++){
	        System.out.println(list[i]);
	    }
	 }
	 
     /**
	 * the method calcThopt() is defined in Thermoptim's Projet class
	 */
	void bRecalcThopt_actionPerformed(java.awt.event.ActionEvent event)
	{
	    try{
	        runThopt();
	    }
        catch(Exception ioexception){
            ioexception.printStackTrace();
        }
	}
	 

	/**
	* Imprime des propriétés d'une transfo et d'un point
    *<p>
	* Prints properties of a process and a point
	*/
	 public void printProperties(){
	    String[] list=proj.getProcessList();
	    String[] args=new String[2];
	    args[0]="process";//type of the element (see method getProperties(String[] args))
	    args[1]=list[1];//name of the process (see method getProperties(String[] args))
	    Vector vProp=proj.getProperties(args);
	    System.out.println("flow : "+vProp.elementAt(3));
	    String amont=(String)vProp.elementAt(1);
	    args[0]="point";//type of the element (see method getProperties(String[] args))
	    args[1]=amont;//name of the point (see method getProperties(String[] args))
	    Vector vProp2=proj.getProperties(args);
	    System.out.println("temp : "+vProp2.elementAt(2));
	 }
	
	/**
	* Recalcule les propriétés d'un point
    *<p>
	* Recalculates a point properties
	*/
	 public void recalcProperties(){
	    String[] list=proj.getProcessList();
	    String[] args=new String[2];
	    args[0]="process";//type of the element (see method getProperties(String[] args))
	    args[1]=list[1];//name of the process (see method getProperties(String[] args))
	    Vector vProp=proj.getProperties(args);
	    String amont=(String)vProp.elementAt(1);//gets the upstream point name
	    getPointProperties(amont);//direct parsing of point property vector
	    System.out.println("Tamont : "+Tpoint);
	    lecorps.CalcPropCorps(1.2*Tpoint, 1.2*Ppoint, Xpoint);//this method recalculates the substance properties 
	    System.out.println("corps : "+nomCorps);
	    getSubstProperties(nomCorps);//direct parsing of substance property vector
	    System.out.println("Hamont avant recalcul : "+Hpoint);
	    System.out.println("Hamont après recalcul : "+Hsubst);
	 }
	
    
    double Tsubst,Psubst,Xsubst,Vsubst,Usubst,Hsubst,Ssubst;
	/**
	* Met à jour les propriétés d'un corps dans Thermoptim
    *<p>
	* Updates a substance's properties in Thermoptim
    * @param nom String (substance's name)
	*/
    public void getSubstProperties(String nom){
	    String[] args=new String[2];
	    args[0]="subst";//type of the element (see method getProperties(String[] args))
	    args[1]=nom;//name of the process (see method getProperties(String[] args))
	    Vector vProp=proj.getProperties(args);
        Double y=(Double)vProp.elementAt(0);
        Tsubst=y.doubleValue();
        y=(Double)vProp.elementAt(1);
	    Psubst=y.doubleValue();
        y=(Double)vProp.elementAt(2);
	    Xsubst=y.doubleValue();
        y=(Double)vProp.elementAt(3);
	    Vsubst=y.doubleValue();
        y=(Double)vProp.elementAt(4);
	    Usubst=y.doubleValue();
        y=(Double)vProp.elementAt(5);
	    Hsubst=y.doubleValue();
        y=(Double)vProp.elementAt(6);
	    Ssubst=y.doubleValue();
    }
    
    double Tpoint,Ppoint,Xpoint,Vpoint,Upoint,Hpoint,DTsatpoint,Spoint;
    Corps lecorps;
    String nomCorps;
    boolean isTsatSet,isPsatSet;
    
    	/**
	* Met à jour les propriétés d'un point dans Thermoptim
    *<p>
	* Updates a point's properties in Thermoptim
    * @param nom String (point's name)
	*/
    public void getPointProperties(String nom){
	    String[] args=new String[2];
	    args[0]="point";//type of the element (see method getProperties(String[] args))
	    args[1]=nom;//name of the process (see method getProperties(String[] args))
	    Vector vProp=proj.getProperties(args);
        lecorps=(Corps)vProp.elementAt(0);
        nomCorps=(String)vProp.elementAt(1);
        Double y=(Double)vProp.elementAt(2);
        Tpoint=y.doubleValue();
        y=(Double)vProp.elementAt(3);
	    Ppoint=y.doubleValue();
        y=(Double)vProp.elementAt(4);
	    Xpoint=y.doubleValue();
        y=(Double)vProp.elementAt(5);
	    Vpoint=y.doubleValue();
        y=(Double)vProp.elementAt(6);
	    Upoint=y.doubleValue();
        y=(Double)vProp.elementAt(7);
	    Hpoint=y.doubleValue();
        y=(Double)vProp.elementAt(8);
	    Spoint=y.doubleValue();
        y=(Double)vProp.elementAt(10);
	    DTsatpoint=y.doubleValue();
	    String dum=(String)vProp.elementAt(9);
	    isTsatSet=lit_b(extr_value(dum));
	    dum=(String)vProp.elementAt(11);
	    isPsatSet=lit_b(extr_value(dum));
    }
    
	/**
	* Fournit les valeurs thermodynamiques des divers éléments
	* Gives thermodynamic values for the various element
	*
	public Vector getProperties(String[] args){
	    String type, nomType;
	    type=args[0];
	    nomType=args[1];
	    Vector vProp=new Vector();
	    
	    if(type.equals("subst")){
	        Corps pt=getCorps(nomType);
	        if(pt!=null){
	            vProp.addElement(new Double(pt.T));//Temperature
	            vProp.addElement(new Double(pt.P));//Pressure
	            vProp.addElement(new Double(pt.xx));//Quality
	            vProp.addElement(new Double(pt.V));//Volume
	            vProp.addElement(new Double(pt.U));//Internal energy
	            vProp.addElement(new Double(pt.H));//Enthalpy
	            vProp.addElement(new Double(pt.S));//Entropy
	        }
	    }
	    else if(type.equals("point")){
	        PointCorps pt=getPoint(nomType);
	        if(pt!=null){
	            vProp.addElement(pt.lecorps);//Substance
	            vProp.addElement(pt.lecorps.getNom());//Substance name
	            vProp.addElement(new Double(pt.getT()));//Temperature
	            vProp.addElement(new Double(pt.getP()));//Pressure
	            vProp.addElement(new Double(pt.getXx()));//Quality
	            vProp.addElement(new Double(pt.getV()));//Volume
	            vProp.addElement(new Double(pt.getU()));//Internal energy
	            vProp.addElement(new Double(pt.getH()));//Enthalpy
	            vProp.addElement(new Double(pt.getS()));//Entropy
	            String setTsat="set_Tsat="+Util.aff_b(pt.JCheckSetTsat.isSelected());
	            vProp.addElement(setTsat);//setTsat
	            vProp.addElement(new Double(pt.dTsat_value.getValue()));//DTsat
	            String setpsat="set_psat="+Util.aff_b(pt.JCheckSetPsat.isSelected());
	            vProp.addElement(setpsat);//setpsat
	        }
	    }
	    else if(type.equals("process")){
	        Transfo tf=getTransfo(nomType);
	        vProp.addElement(tf.getType());
	        if(tf!=null){
	            vProp.addElement(tf.getPointAmont().getName());
	            vProp.addElement(tf.getPointAval().getName());
	            vProp.addElement(new Double(tf.getFlow()));//flow rate
	            vProp.addElement(new Double(tf.DeltaH));//Enthalpy
	            vProp.addElement(tf.ener_type_value.getText());//Energy type
	            String direct="calcDirect="+Util.aff_b(tf.IcalcDirect);
	            vProp.addElement(direct);//true if direct calculation
	            String ouvert="openSyst="+Util.aff_b(tf.JCheckOuvert.isSelected());
	            vProp.addElement(ouvert);//true for open system
	            String setflow="setFlow="+Util.aff_b(tf.JCheckSetFlow.isSelected());
	            vProp.addElement(setflow);//true for set flow
	            if(tf instanceof Combustion){
	                Combustion cb=(Combustion)tf;
	                vProp.addElement(cb.getFuel().getName());
	                vProp.addElement(new Double(cb.lambda_value.getValue()));//lambda
	                vProp.addElement(new Double(cb.Tfluegas));//combustion temperature
	                vProp.addElement(new Double(cb.tfig_value.getValue()));//quenching temperature
	                vProp.addElement(new Double(cb.t_diss_value.getValue()));//dissociation rate
	                vProp.addElement(new Double(cb.lambda_value.getValue()));
		            String calcLambda="calcLambda="+Util.aff_b(tf.JCheckCalcLambda.isSelected());
	                vProp.addElement(calcLambda);//true if calculate lambda set
		            String calcT="calcT="+Util.aff_b(tf.JCheckCalcT.isSelected());
	                vProp.addElement(calcT);//true if calculate T set
		            String setFuelFlow="setFuelFlow="+Util.aff_b(tf.JCheckFuelFlow.isSelected());
	                vProp.addElement(setFuelFlow);//true if calculate with set fuel flow 
		            String dissoc="setDissoc="+Util.aff_b(tf.Check_dissoc.isSelected());
	                vProp.addElement(dissoc);//true if dissociation set
                }
	        }	    
	    }
	    else if(type.equals("node")){
	        Node nd=getNode(nomType);
	        if(nd!=null){
	            
	        }
	    }
	    else if(type.equals("heatEx")){
	        HeatExDemo hX=getHX(nomType);
	        if(hX!=null){
	            vProp.addElement(hX.getHotFluid().getName());
	            vProp.addElement(hX.getColdFluid().getName());
	            vProp.addElement(new Double(hX.R));
	            vProp.addElement(new Double(hX.NUT));
	            vProp.addElement(new Double(hX.UA));
	            vProp.addElement(new Double(hX.DTML));
	            vProp.addElement(new Double(hX.epsi_value.getValue()));
	        }
	    }
	    return vProp;
	}
    
*/

    /**
    * utility method
    * 
    * extracts the String at the right of the '=' character
    * 
    * @param s original String "value=3.4"
    * @return java.lang.String
    */
    public static String extr_value(String s) {
        int ind_egal=s.indexOf((int)'=');
        if(ind_egal<s.length())
	    return s.substring(ind_egal+1);
	    return null;
    }


    /** 
    * reads a boolean
    *<p>
    * lecture d'un booléen
    * @return boolean
    * @param s "true" or "false"
    */
    public static boolean lit_b(String s) {
	    Boolean BB;
	    BB=new Boolean(s);
	    return BB.booleanValue();
    }

	void bCancel_actionPerformed(java.awt.event.ActionEvent event)
	{
		System.exit(0);
	}

	class SymItem implements java.awt.event.ItemListener
	{
		public void itemStateChanged(java.awt.event.ItemEvent event)
		{
		}
	}
}