package simpleEquilibriumDiagrams;

import lib.common.MsgExceptn;

/** Show a frame with the program version, acknowledgements, etc
 * <br>
 * Copyright (C) 2014-2020 I.Puigdomenech.
 * 
 * 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 3 of the License, or
 * 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, see http://www.gnu.org/licenses/
 * 
 * @author Ignasi Puigdomenech */
public class HelpAboutF extends javax.swing.JFrame {
  private boolean finished = false;
  private HelpAboutF frame = null;
  /** Where errors will be printed. It may be <code>System.err</code>.
   * If null, <code>System.err</code> is used. */
  private final java.io.PrintStream out;
  /** New-line character(s) to substitute "\n" */
  private static final String nl = System.getProperty("line.separator");

  /** Creates new form HelpAboutF
   * @param vers A text providing the program version
   * @param pathApp path where the application is located
   * @param out0 Where errors will be printed. For example <code>System.out</code>.
   * If null, <code>System.err</code> is used */
  public HelpAboutF(final String vers, final String pathApp, java.io.PrintStream out0) {
    if(out0 != null) {this.out = out0;} else {this.out = System.out;}
    finished = false;
    initComponents();
    setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
    //--- Close window on ESC key
    javax.swing.KeyStroke escKeyStroke = javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_ESCAPE,0, false);
    getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(escKeyStroke,"ESCAPE");
    javax.swing.Action escAction = new javax.swing.AbstractAction() {
        @Override public void actionPerformed(java.awt.event.ActionEvent e) {
            closeWindow();
        }};
    getRootPane().getActionMap().put("ESCAPE", escAction);
    //--- Alt-X eXit
    javax.swing.KeyStroke altXKeyStroke = javax.swing.KeyStroke.getKeyStroke(
            java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.ALT_MASK, false);
    getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altXKeyStroke,"ALT_X");
    getRootPane().getActionMap().put("ALT_X", escAction);
    //--- alt-Q exit
    javax.swing.KeyStroke altQKeyStroke = javax.swing.KeyStroke.getKeyStroke(
                java.awt.event.KeyEvent.VK_Q, java.awt.event.InputEvent.ALT_MASK, false);
    getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altQKeyStroke,"ALT_Q");
    getRootPane().getActionMap().put("ALT_Q", escAction);

    //--- Title, etc
    //getContentPane().setBackground(java.awt.Color.white);
    this.setTitle(SED.progName+": About");
    //---- Icon
    String iconName = "images/Question_16x16.gif";
    java.net.URL imgURL = this.getClass().getResource(iconName);
    if (imgURL != null) {this.setIconImage(new javax.swing.ImageIcon(imgURL).getImage());}
    else {out.println("Error: Could not load image = \""+iconName+"\"");}

    jLabelVers.setText("Program version: "+vers);
    jLabelPathApp.setText(pathApp);
    jLabelPathUser.setText(System.getProperty("user.home"));
    this.validate();
    int w = jLabelPathApp.getWidth()+40;
    if(w > this.getWidth()) {this.setSize(w, this.getHeight());}
    // Centre the window on the screen
    int left = Math.max(0,(SED.screenSize.width-this.getWidth())/2);
    int top = Math.max(0,(SED.screenSize.height-this.getHeight())/2);
    this.setLocation(Math.min(SED.screenSize.width-100, left),
                     Math.min(SED.screenSize.height-100, top));
    javax.swing.SwingUtilities.invokeLater(new Runnable() {@Override public void run() {
        frame = HelpAboutF.this;
    }}); //invokeLater(Runnable)
  } //constructor

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel_Name = new javax.swing.JLabel();
        jLabelVers = new javax.swing.JLabel();
        jLabelLicense = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        jLabelJava = new javax.swing.JLabel();
        jLabelPathA = new javax.swing.JLabel();
        jLabelPathApp = new javax.swing.JLabel();
        jLabelPathU = new javax.swing.JLabel();
        jLabelPathUser = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        jLabel_wwwKTH = new javax.swing.JLabel();
        jLabel_www = new javax.swing.JLabel();
        jLabelUnicode = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        jLabel_Name.setText("<html><b><font size=+1>SED</font></b> &nbsp;&nbsp;<b>S</b>imple <b>E</b>quilibrium <b>D</b>iagrams<br>\n© 2020 &nbsp; I.Puigdomenech,<br>\nHaltafall algorithm by Ingri <i>et al</i> (1967).</html>");

        jLabelVers.setText("LabelVers");

        jLabelLicense.setText("<html>This program comes with ABSOLUTELY NO WARRANTY.<br>This is free software, and you are welcome to redistribute it<br>under the GNU GPL license. See file \"GPL.txt\".</html>");

        jLabelJava.setText("<html>Java Standard Edition<br>Development Kit 7 (JDK 1.7)<br>NetBeans IDE</html>");

        jLabelPathA.setLabelFor(jLabelPathApp);
        jLabelPathA.setText("Application path:");

        jLabelPathApp.setText("\"null\"");

        jLabelPathU.setText("User \"home\" directory:");

        jLabelPathUser.setText("\"null\"");

        jLabel_wwwKTH.setForeground(new java.awt.Color(0, 0, 221));
        jLabel_wwwKTH.setText("<html><u>www.kth.se/che/medusa</u></html>");
        jLabel_wwwKTH.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        jLabel_wwwKTH.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jLabel_wwwKTHMouseClicked(evt);
            }
        });

        jLabel_www.setForeground(new java.awt.Color(0, 0, 221));
        jLabel_www.setText("<html><u>sites.google.com/site/chemdiagr/</u></html>");
        jLabel_www.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        jLabel_www.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jLabel_wwwMouseClicked(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel_wwwKTH, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel_www, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(26, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jLabel_wwwKTH, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jLabel_www, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        jLabelUnicode.setText("(Unicode UTF-8)");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jSeparator1)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jLabel_Name, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(18, 18, 18)
                                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addComponent(jLabelJava, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jLabelPathA)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(jLabelPathApp)))
                                .addGap(0, 11, Short.MAX_VALUE)))
                        .addContainerGap())
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabelLicense, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabelVers)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabelUnicode))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabelPathU)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabelPathUser)))
                        .addGap(0, 0, Short.MAX_VALUE))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(5, 5, 5)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel_Name, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabelVers)
                    .addComponent(jLabelUnicode))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabelLicense, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 4, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabelJava, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabelPathA)
                    .addComponent(jLabelPathApp))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabelPathU)
                    .addComponent(jLabelPathUser))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jLabel_wwwMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel_wwwMouseClicked
        BareBonesBrowserLaunch.openURL("https://sites.google.com/site/chemdiagr/",this);
}//GEN-LAST:event_jLabel_wwwMouseClicked

    private void jLabel_wwwKTHMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel_wwwKTHMouseClicked
        BareBonesBrowserLaunch.openURL("https://www.kth.se/che/medusa/",this);
}//GEN-LAST:event_jLabel_wwwKTHMouseClicked

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        closeWindow();
    }//GEN-LAST:event_formWindowClosing

  public void closeWindow() {
    finished = true;
    this.notify_All();
    this.dispose();
  } // closeWindow()
  private synchronized void notify_All() {notifyAll();}
  /** this method will wait for this dialog frame to be closed */
  public synchronized void waitFor() {
    while(!finished) {
        try {wait();} catch (InterruptedException ex) {}
    } // while
  } // waitFor()
  public void bringToFront() {
    if(frame != null) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override public void run() {
                frame.setVisible(true);
                if((frame.getExtendedState() & javax.swing.JFrame.ICONIFIED) // minimised?
                            == javax.swing.JFrame.ICONIFIED) {
                    frame.setExtendedState(javax.swing.JFrame.NORMAL);
                } // if minimized
                frame.setAlwaysOnTop(true);
                frame.toFront();
                frame.requestFocus();
                frame.setAlwaysOnTop(false);
            }
        });
    }
  } // bringToFront()

  //<editor-fold defaultstate="collapsed" desc="class BareBonesBrowserLaunch">

/**
 * <b>Bare Bones Browser Launch for Java</b><br>
 * Utility class to open a web page from a Swing application
 * in the user's default browser.<br>
 * Supports: Mac OS X, GNU/Linux, Unix, Windows XP/Vista/7<br>
 * Example Usage:<code><br> &nbsp; &nbsp;
 *    String url = "http://www.google.com/";<br> &nbsp; &nbsp;
 *    BareBonesBrowserLaunch.openURL(url);<br></code>
 * Latest Version: <a href=http://centerkey.com/java/browser>centerkey.com/java/browser</a><br>
 * Author: Dem Pilafian<br>
 * WTFPL -- Free to use as you like
 * @version 3.2, October 24, 2010
 */
private static class BareBonesBrowserLaunch {

   static final String[] browsers = { "x-www-browser", "google-chrome",
      "firefox", "opera", "epiphany", "konqueror", "conkeror", "midori",
      "kazehakase", "mozilla", "chromium" };  // modified by Ignasi (added "chromium")
   static final String errMsg = "Error attempting to launch web browser";

   /**
    * Opens the specified web page in the user's default browser
    * @param url A web address (URL) of a web page (ex: "http://www.google.com/")
    */
   public static void openURL(String url, javax.swing.JFrame parent) {  // modified by Ignasi (added "parent")
      try {  //attempt to use Desktop library from JDK 1.6+
         Class<?> d = Class.forName("java.awt.Desktop");
         d.getDeclaredMethod("browse", new Class[] {java.net.URI.class}).invoke(
            d.getDeclaredMethod("getDesktop").invoke(null),
            new Object[] {java.net.URI.create(url)});
         //above code mimicks:  java.awt.Desktop.getDesktop().browse()
         }
      catch (Exception ignore) {  //library not available or failed
         String osName = System.getProperty("os.name");
         try {
            if (osName.startsWith("Mac OS")) {
               Class.forName("com.apple.eio.FileManager").getDeclaredMethod(
                  "openURL", new Class[] {String.class}).invoke(null,new Object[] {url});
            }
            else if (osName.startsWith("Windows"))
               Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url);
            else { //assume Unix or Linux
               String browser = null;
               for (String b : browsers)
                  if (browser == null && Runtime.getRuntime().exec(new String[]
                        {"which", b}).getInputStream().read() != -1)
                     Runtime.getRuntime().exec(new String[] {browser = b, url});
               if (browser == null)
                  throw new Exception(java.util.Arrays.toString(browsers));
            }
         }
         catch (Exception e) {
            MsgExceptn.exception(errMsg + "\n" + e.getMessage()); // added by Ignasi
            javax.swing.JOptionPane.showMessageDialog(parent, errMsg + "\n" + e.getMessage(), // modified by Ignasi (added "parent")
                    "Chemical Equilibrium Diagrams", javax.swing.JOptionPane.ERROR_MESSAGE);  // added by Ignasi
         }
      }
   }

}
  //</editor-fold>

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabelJava;
    private javax.swing.JLabel jLabelLicense;
    private javax.swing.JLabel jLabelPathA;
    private javax.swing.JLabel jLabelPathApp;
    private javax.swing.JLabel jLabelPathU;
    private javax.swing.JLabel jLabelPathUser;
    private javax.swing.JLabel jLabelUnicode;
    private javax.swing.JLabel jLabelVers;
    private javax.swing.JLabel jLabel_Name;
    private javax.swing.JLabel jLabel_www;
    private javax.swing.JLabel jLabel_wwwKTH;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JSeparator jSeparator1;
    // End of variables declaration//GEN-END:variables

}
