package addShowRefs;

import lib.database.References;

/** Save references to a reference file.
 *
 * 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 EditAddRefs extends javax.swing.JFrame {
  private References r = null;
  private boolean finished;
  private String theKey;

  private java.awt.Dimension windowSize = new java.awt.Dimension(400,280);

  /** New-line character(s) to substitute "\n" */
  private static final String nl = System.getProperty("line.separator");

  /** Creates new form EditAddRefs
   * @param r0 */
  public EditAddRefs(References r0) {
    initComponents();
    this.r = r0;
    finished = false;
    jTextArea.setWrapStyleWord(true);
    //--- Ctrl-S save
    javax.swing.KeyStroke ctrlSKeyStroke = javax.swing.KeyStroke.getKeyStroke(
            java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_MASK, false);
    getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(ctrlSKeyStroke,"CTRL_S");
    javax.swing.Action ctrlSAction = new javax.swing.AbstractAction() {
        @Override public void actionPerformed(java.awt.event.ActionEvent e) {
            jButtonSave.doClick();
        }};
    getRootPane().getActionMap().put("CTRL_S", ctrlSAction);
    //---- Position the window on the screen
    java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
    java.awt.Point frameLocation = new java.awt.Point(-1000,-1000);
    frameLocation.x = Math.max(0, (screenSize.width  - this.getWidth() ) / 2);
    frameLocation.y = Math.max(0, (screenSize.height - this.getHeight() ) / 2);
    this.setLocation(frameLocation);
    this.setTitle("Save a reference");
    //---- Icon
    String iconName = "images/Refs.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+"\"");}
    theKey = "";
  }
    public void start() {
        //---- Title
        this.setTitle("Show references");
        jTextFieldKey.setText("");
        String t = r.referencesFileName();
        if(t == null) {
            javax.swing.JOptionPane.showMessageDialog(
                    this, "No reference file!?", "Add References",
                    javax.swing.JOptionPane.ERROR_MESSAGE);
            jButtonQuit.doClick();
            return;
        } else {jLabelFileName.setText(t);}
        windowSize = this.getSize();
    }
    public void start(String key, String ref) {
        //---- Title
        this.setTitle("Edit reference");
        if(key == null || key.trim().length() <=0) {
            javax.swing.JOptionPane.showMessageDialog(
                    this, "No key!?", "Edit Reference",
                    javax.swing.JOptionPane.ERROR_MESSAGE);
            jButtonQuit.doClick();
            return;
        }
        if(ref == null || ref.trim().length() <=0) {ref="";}
        jTextFieldKey.setText(key);
        jTextFieldKey.setEditable(false);
        jTextFieldKey.setBackground(java.awt.Color.LIGHT_GRAY);
        jTextArea.setText(ref);
        jTextArea.setCaretPosition(0);
        String t = r.referencesFileName();
        if(t == null) {
            javax.swing.JOptionPane.showMessageDialog(
                    this, "No reference file!?", "Edit Reference",
                    javax.swing.JOptionPane.ERROR_MESSAGE);
            jButtonQuit.doClick();
            return;
        } else {jLabelFileName.setText(t);}
        windowSize = this.getSize();
    }

    /** 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() {
        java.awt.GridBagConstraints gridBagConstraints;

        jPanel1 = new javax.swing.JPanel();
        jLabel0 = new javax.swing.JLabel();
        jLabelFileName = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jTextFieldKey = new javax.swing.JTextField();
        jPanel3 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jScrollPane = new javax.swing.JScrollPane();
        jTextArea = new javax.swing.JTextArea();
        jPanel4 = new javax.swing.JPanel();
        jButtonSave = new javax.swing.JButton();
        jButtonQuit = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentResized(java.awt.event.ComponentEvent evt) {
                formComponentResized(evt);
            }
        });
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });
        getContentPane().setLayout(new java.awt.GridBagLayout());

        jPanel1.setLayout(new java.awt.BorderLayout());

        jLabel0.setText("Reference file:");
        jPanel1.add(jLabel0, java.awt.BorderLayout.NORTH);

        jLabelFileName.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabelFileName.setText("jLabel4");
        jPanel1.add(jLabelFileName, java.awt.BorderLayout.SOUTH);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.ipady = 2;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(2, 5, 12, 0);
        getContentPane().add(jPanel1, gridBagConstraints);

        jPanel2.setLayout(new java.awt.BorderLayout());

        jLabel1.setLabelFor(jTextFieldKey);
        jLabel1.setText("Reference Key:");
        jPanel2.add(jLabel1, java.awt.BorderLayout.NORTH);
        jPanel2.add(jTextFieldKey, java.awt.BorderLayout.SOUTH);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(0, 5, 13, 5);
        getContentPane().add(jPanel2, gridBagConstraints);

        jPanel3.setLayout(new java.awt.GridBagLayout());

        jLabel2.setLabelFor(jTextArea);
        jLabel2.setText("Reference contents:");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
        jPanel3.add(jLabel2, gridBagConstraints);

        jScrollPane.setFont(new java.awt.Font("Monospaced", 0, 13)); // NOI18N

        jTextArea.setColumns(20);
        jTextArea.setLineWrap(true);
        jTextArea.setRows(5);
        jScrollPane.setViewportView(jTextArea);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        jPanel3.add(jScrollPane, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(0, 5, 10, 5);
        getContentPane().add(jPanel3, gridBagConstraints);

        jPanel4.setLayout(new java.awt.BorderLayout());

        jButtonSave.setMnemonic('s');
        jButtonSave.setText(" Save ");
        jButtonSave.setAlignmentX(0.5F);
        jButtonSave.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
        jButtonSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonSaveActionPerformed(evt);
            }
        });
        jPanel4.add(jButtonSave, java.awt.BorderLayout.WEST);

        jButtonQuit.setMnemonic('q');
        jButtonQuit.setText(" Quit ");
        jButtonQuit.setAlignmentX(0.5F);
        jButtonQuit.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
        jButtonQuit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonQuitActionPerformed(evt);
            }
        });
        jPanel4.add(jButtonQuit, java.awt.BorderLayout.EAST);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.PAGE_END;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(0, 6, 5, 5);
        getContentPane().add(jPanel4, gridBagConstraints);

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

    private void jButtonQuitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonQuitActionPerformed
        quitFrame();
    }//GEN-LAST:event_jButtonQuitActionPerformed

    private void jButtonSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSaveActionPerformed
    
      if(jTextFieldKey.getText() == null || jTextFieldKey.getText().trim().length()<=0) {
          javax.swing.JOptionPane.showMessageDialog(this,"Error:"+nl+"Reference Key may not be empty!",
                  "Save References",javax.swing.JOptionPane.ERROR_MESSAGE);
          return;
      }
      String key = jTextFieldKey.getText().trim();
      String newRef = jTextArea.getText();
      if(!r.readRefsFile(jLabelFileName.getText(), false)) {
        System.out.println("Properties not loaded from file \""+jLabelFileName.getText()+"\""+nl+"quitting ...");
        return;
      }
      if(newRef == null || newRef.trim().length()<=0) {
          String oldRef = r.isRefThere(key);
          if(oldRef != null) {
            String msg = "Delete existing reference?"+nl+nl+
                         key+" = "+oldRef+nl+" ";
            Object[] opt = {"Yes", "Cancel"};
            int m = javax.swing.JOptionPane.showOptionDialog(this,
                msg,
                "Save References", javax.swing.JOptionPane.YES_NO_OPTION,
                javax.swing.JOptionPane.WARNING_MESSAGE, null, opt, opt[1]);
            if(m != javax.swing.JOptionPane.YES_OPTION) {return;}
          } else {
              javax.swing.JOptionPane.showMessageDialog(this, "No reference text to save", "Save References", javax.swing.JOptionPane.QUESTION_MESSAGE);
              return;
          }
          newRef = null;
      } else {  // newRef not empty
          newRef = newRef.trim();
          String found = r.isRefThere(key);
          if(found != null && found.trim().length() >=0) {
            String msg = "Replace reference?"+nl+nl;
            Object[] opt = {"Yes", "Cancel"};
            int m = javax.swing.JOptionPane.showOptionDialog(this, msg,
                "Save References", javax.swing.JOptionPane.YES_NO_OPTION,
                javax.swing.JOptionPane.WARNING_MESSAGE, null, opt, opt[1]);
            if(m != javax.swing.JOptionPane.YES_OPTION) {return;}
          }
      }  // newRef empty?

      r.setRef(key, newRef);

      r.saveRefsFile(this, false);
      theKey = key;
      jTextFieldKey.setText("");
      jTextArea.setText("");
      jButtonQuit.doClick();
    }//GEN-LAST:event_jButtonSaveActionPerformed

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

    private void formComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentResized
      if(windowSize != null) {
        int w = windowSize.width;
        int h = windowSize.height;
        if(this.getHeight()<h){this.setSize(this.getWidth(), h);}
        if(this.getWidth()<w){this.setSize(w,this.getHeight());}
      }
    }//GEN-LAST:event_formComponentResized

  private void quitFrame() {
    finished = true;
    this.notify_All();
    this.dispose();
  }
  private synchronized void notify_All() {notifyAll();}

  /** this method will wait for this dialog frame to be closed
   * @return the key to the reference saved if the user presses the "OK" button,
   * or an empty string if the edit is cancelled.
   */
  public synchronized String waitFor() {
    while(!finished) {
        try {wait();} catch (InterruptedException ex) {}
    } // while
    return theKey;
  } // waitFor()

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonQuit;
    private javax.swing.JButton jButtonSave;
    private javax.swing.JLabel jLabel0;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabelFileName;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JScrollPane jScrollPane;
    private javax.swing.JTextArea jTextArea;
    private javax.swing.JTextField jTextFieldKey;
    // End of variables declaration//GEN-END:variables
}
