package database;

import lib.huvud.ProgramConf;
import lib.huvud.RedirectedFrame;

/** Disclaimer for the Database program.
 * <br>
 * Copyright (C) 2015-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 Disclaimer extends javax.swing.JFrame {
  private final FrameDBmain dbF;
  private final ProgramConf pc;
  private boolean accepted = false;
  private boolean finished = false;
  private final RedirectedFrame msgFrame;

  //<editor-fold defaultstate="collapsed" desc="Constructor">
 /**
  * Creates new form Disclaimer
  * @param parent
  * @param pc0 program configuration
  * @param msgFrame0
  */
  public Disclaimer(java.awt.Frame parent, ProgramConf pc0, RedirectedFrame msgFrame0) {
    pc = pc0;
    dbF = (FrameDBmain)parent;
    initComponents();
    msgFrame = msgFrame0;

    setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
    setResizable(false);

    //--- close window on ESC key
    javax.swing.KeyStroke escKeyStroke = javax.swing.KeyStroke.getKeyStroke(
                    java.awt.event.KeyEvent.VK_ESCAPE,0, false);
    javax.swing.Action escAction = new javax.swing.AbstractAction() {
        @Override public void actionPerformed(java.awt.event.ActionEvent e) {
            Object[] opt = {"Yes", "No"};
            int answer = javax.swing.JOptionPane.showOptionDialog(Disclaimer.this,
                        "Quit?",
                        pc.progName, javax.swing.JOptionPane.YES_NO_OPTION,
                        javax.swing.JOptionPane.QUESTION_MESSAGE,null, opt, opt[1]);
            accepted = false;
            if(answer == javax.swing.JOptionPane.YES_OPTION) {closeWindow(accepted);}
        }};
    getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(escKeyStroke,"ESCAPE");
    getRootPane().getActionMap().put("ESCAPE", escAction);
    //--- Return = exit
    javax.swing.KeyStroke enterKeyStroke = javax.swing.KeyStroke.getKeyStroke(
            java.awt.event.KeyEvent.VK_ENTER, 0, false);
    javax.swing.Action enterAction = new javax.swing.AbstractAction() {
        @Override public void actionPerformed(java.awt.event.ActionEvent e) {
            jButtonOK.doClick();
        }};
    getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(enterKeyStroke,"_Enter");
    getRootPane().getActionMap().put("_Enter", enterAction);

    //---- Title, etc
    this.setTitle(pc.progName+" - Disclaimer");
    // ---- Icon
    String iconName = "images/DataBase.gif";
    java.net.URL imgURL = this.getClass().getResource(iconName);
    if (imgURL != null) {this.setIconImage(new javax.swing.ImageIcon(imgURL).getImage());}
    else {System.out.println("Error: Could not load image = \""+iconName+"\"");}

    //---- Centre window on parent/screen
    int left,top;
    java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
    left = Math.max(0,(screenSize.width-this.getWidth())/2);
    top = Math.max(0,(screenSize.height-this.getHeight())/2);
    this.setLocation(Math.min(screenSize.width-this.getWidth()-20,left),
                     Math.min(screenSize.height-this.getHeight()-20, top));

    setVisible(true);
    setAlwaysOnTop(true);
    toFront();
    jButtonOK.requestFocus();
    setAlwaysOnTop(false);
    start();
  } // constructor
  private void start(){msgFrame.setParentFrame(this);}
  // </editor-fold>

    /**
     * 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() {

        jLabelDisclTitle = new javax.swing.JLabel();
        jScrollPanelDiscl = new javax.swing.JScrollPane();
        jLabelDiscl = new javax.swing.JLabel();
        jButtonOK = new javax.swing.JButton();

        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });
        addWindowStateListener(new java.awt.event.WindowStateListener() {
            public void windowStateChanged(java.awt.event.WindowEvent evt) {
                formWindowStateChanged(evt);
            }
        });

        jLabelDisclTitle.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        jLabelDisclTitle.setText("<html>Only for <u>students</u>!</html>");

        jScrollPanelDiscl.setBackground(new java.awt.Color(255, 255, 255));

        jLabelDiscl.setBackground(new java.awt.Color(255, 255, 255));
        jLabelDiscl.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabelDiscl.setText("<html>\n<p><font size=+1><b>Please note:</b>&nbsp;</font>\nThis software (including its database) is only<br>\nintended for educational activities. &nbsp; The database may contain:\n<ul><li><b>errors</b> and <b>inconsistencies</b> in the data,</li>\n<li><b>non-existing compounds</b> may be included, and</li>\n<li><b>well known species may be missing.</b></li>\n</ul></p>\n\n<p>You alone are solely responsible for any consequences from<br>\nusing this software in professional and/or research activites.<br>&nbsp;</p>\n\n<p><strong>Disclaimer of Warranty.</strong></p>\n\n<p><font size=-1>THERE IS NO WARRANTY FOR THIS SOFTWARE, TO THE EXTENT PERMITTED<br>\nBY APPLICABLE LAW. &nbsp; EXCEPT WHEN OTHERWISE STATED IN WRITING<br>\nTHE COPYRIGHT HOLDERS AND/OR OTHER PARTIES  PROVIDE THE<br>\nPROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED<br>\nOR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES<br>\nOF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.<br>\nTHE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THIS<br>\nSOFTWARE IS WITH YOU. &nbsp; SHOULD THIS SOFTWARE (OR ITS DATABASE)<br>\nPROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,<br>\nREPAIR OR CORRECTION.</font></p>\n\n<br><p><strong>Limitation of Liability.</strong></p>\n<p><font size=-1>IN NO EVENT UNLESS RE QUIRED BY APPLICABLE LAW OR AGREED TO<br>\nIN WRITING WILL ANY COPYRIGH HOLDER, OR ANY OTHER PARTY WHO<br>\nMODIFIES AND/OR CONVEYS THE PROGRAM, BE LIABLE TO YOU FOR<br>\nDAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR<br>\nCONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO<br>\nUSE THIS SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA<br>\nOR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU<br>\nOR THIRD PARTIES OR A FAILURE OF THIS SOFTWARE TO OPERATE<br>\nWITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER<br>\nPARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.</font></p>\n</html>");
        jLabelDiscl.setVerticalAlignment(javax.swing.SwingConstants.TOP);
        jLabelDiscl.setOpaque(true);
        jScrollPanelDiscl.setViewportView(jLabelDiscl);

        jButtonOK.setMnemonic('A');
        jButtonOK.setText(" Accept ");
        jButtonOK.setAlignmentX(0.5F);
        jButtonOK.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
        jButtonOK.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonOKActionPerformed(evt);
            }
        });

        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()
                        .addComponent(jLabelDisclTitle, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addComponent(jScrollPanelDiscl, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 493, Short.MAX_VALUE))
                .addContainerGap())
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jButtonOK, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(48, 48, 48))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabelDisclTitle, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPanelDiscl, javax.swing.GroupLayout.PREFERRED_SIZE, 337, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButtonOK)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

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

  //<editor-fold defaultstate="collapsed" desc="Events">
    private void jButtonOKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonOKActionPerformed
        accepted = true;
        closeWindow(accepted);
    }//GEN-LAST:event_jButtonOKActionPerformed

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

    private void formWindowStateChanged(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowStateChanged
        if((getExtendedState() & javax.swing.JFrame.ICONIFIED) // minimised?
                            == javax.swing.JFrame.ICONIFIED) {
                    setExtendedState(javax.swing.JFrame.NORMAL);
        }
        setAlwaysOnTop(true);
        toFront();
        jButtonOK.requestFocus();
        setAlwaysOnTop(false);
    }//GEN-LAST:event_formWindowStateChanged
  // </editor-fold>

  //<editor-fold defaultstate="collapsed" desc="closeWindow(accepted)">
  /** Closes the Disclaimer window, displays the main window.
   * If the user has not "accepted" the disclaimer, the program is ended.
   * @param disclaimerAccepted */
  public void closeWindow(boolean disclaimerAccepted) {
    if(!disclaimerAccepted) {dbF.end_program();}
    finished = true;
    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 waitForDisclaimer() {
    while(!finished) {
        try {wait();} catch (InterruptedException ex) {}
    } // while
  } // waitForDisclaimer()
  // </editor-fold>

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonOK;
    private javax.swing.JLabel jLabelDiscl;
    private javax.swing.JLabel jLabelDisclTitle;
    private javax.swing.JScrollPane jScrollPanelDiscl;
    // End of variables declaration//GEN-END:variables
}
