package audiobook;

import java.awt.event.ActionEvent;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringReader;
import javax.swing.AbstractAction;
import javax.swing.JFileChooser;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.JTextArea;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import other.Strings.QuoteProcessor;
import swing.Beans.MultipleInputPane;

/**
 * A class providing a JFrame to display a simple {@link javax.swing.JTextArea} to edit text.
 * @author Kim
 * @see JTextArea
 * @see NumberQuoteProcessor
 * @see M4aTagQuoteProcessor
 * @see FileNameQuoteProcessor
 * @see AdvancedFileNameQuoteProcessor
 * @see FilepathQuoteProcessor
 * @see QuoteProcessor
 */
public class ChapterProfileCreator extends javax.swing.JFrame {

    /** Creates new form ChapterProfileCreator */
    public ChapterProfileCreator() {
        initComponents();
        textArea.getDocument().addDocumentListener(new DocumentListener() {

            @Override
            public void insertUpdate(DocumentEvent e) {
                if ((!textArea.getText().equals(lastText))) {
                    isSaved = false;
                }
                if (textArea.getText() == null || textArea.getText() == "") {
                    isSaved = true;
                }
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                if (!textArea.getText().equals(lastText)) {
                    isSaved = false;
                }
                if (textArea.getText() == null || textArea.getText() == "") {
                    isSaved = true;
                }
            }

            @Override
            public void changedUpdate(DocumentEvent e) {
                if (!textArea.getText().equals(lastText)) {
                    isSaved = false;
                }
                if (textArea.getText() == null || textArea.getText() == "") {
                    isSaved = true;
                }
            }
        });
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        addPanel = new javax.swing.JPanel();
        NumberButton = new javax.swing.JButton();
        FileNameButton = new javax.swing.JButton();
        FilePathButton = new javax.swing.JButton();
        TagButton = new javax.swing.JButton();
        CommentButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        textArea = new javax.swing.JTextArea();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        UseNowMenuItem = new javax.swing.JMenuItem();
        jSeparator2 = new javax.swing.JPopupMenu.Separator();
        SaveMenuItem = new javax.swing.JMenuItem();
        OpenMenuItem = new javax.swing.JMenuItem();
        SaveAsMenuItem = new javax.swing.JMenuItem();
        jSeparator1 = new javax.swing.JPopupMenu.Separator();
        CloseMenuItem = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setTitle("Kapitelprofil Editor");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        addPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Hinzufügen"));

        NumberButton.setText("Kapitelnummer");
        NumberButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                NumberButtonActionPerformed(evt);
            }
        });

        FileNameButton.setText("Dateinamen");
        FileNameButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                FileNameButtonActionPerformed(evt);
            }
        });

        FilePathButton.setText("Dateipfad");
        FilePathButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                FilePathButtonActionPerformed(evt);
            }
        });

        TagButton.setText("Tag");
        TagButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                TagButtonActionPerformed(evt);
            }
        });

        CommentButton.setText("Vorschau Kommentar");
        CommentButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CommentButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout addPanelLayout = new javax.swing.GroupLayout(addPanel);
        addPanel.setLayout(addPanelLayout);
        addPanelLayout.setHorizontalGroup(
            addPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(addPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(addPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(NumberButton, javax.swing.GroupLayout.DEFAULT_SIZE, 209, Short.MAX_VALUE)
                    .addComponent(FileNameButton, javax.swing.GroupLayout.DEFAULT_SIZE, 209, Short.MAX_VALUE)
                    .addComponent(FilePathButton, javax.swing.GroupLayout.DEFAULT_SIZE, 209, Short.MAX_VALUE)
                    .addComponent(TagButton, javax.swing.GroupLayout.DEFAULT_SIZE, 209, Short.MAX_VALUE)
                    .addComponent(CommentButton, javax.swing.GroupLayout.DEFAULT_SIZE, 209, Short.MAX_VALUE)))
        );
        addPanelLayout.setVerticalGroup(
            addPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(addPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(NumberButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(FileNameButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(FilePathButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(TagButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(CommentButton)
                .addGap(53, 53, 53))
        );

        textArea.setColumns(20);
        textArea.setRows(5);
        textArea.setDragEnabled(true);
        jScrollPane1.setViewportView(textArea);

        jMenu1.setText("Datei");

        UseNowMenuItem.setText("In Hörbuch übernehmen");
        UseNowMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                UseNowMenuItemActionPerformed(evt);
            }
        });
        jMenu1.add(UseNowMenuItem);
        jMenu1.add(jSeparator2);

        SaveMenuItem.setText("Speichern");
        SaveMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                SaveMenuItemActionPerformed(evt);
            }
        });
        jMenu1.add(SaveMenuItem);

        OpenMenuItem.setText("Öffnen");
        OpenMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                OpenMenuItemActionPerformed(evt);
            }
        });
        jMenu1.add(OpenMenuItem);

        SaveAsMenuItem.setText("Speichern unter...");
        SaveAsMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                SaveAsMenuItemActionPerformed(evt);
            }
        });
        jMenu1.add(SaveAsMenuItem);
        jMenu1.add(jSeparator1);

        CloseMenuItem.setText("Schließen");
        CloseMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CloseMenuItemActionPerformed(evt);
            }
        });
        jMenu1.add(CloseMenuItem);

        jMenuBar1.add(jMenu1);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 480, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(addPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 232, Short.MAX_VALUE)
                    .addComponent(addPanel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 232, Short.MAX_VALUE))
                .addContainerGap())
        );

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

    /**
     * Adds text to the TextArea to use the chapter number
     * @param evt Auto generated event; Not used
     */
private void NumberButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_NumberButtonActionPerformed
    JPopupMenu menu = new JPopupMenu();
    JMenuItem normal = new JMenuItem(new AbstractAction("Normal") {

        @Override
        public void actionPerformed(ActionEvent e) {
            textArea.append("<%number<formatted='false'>>");
        }
    });
    JMenuItem formatted = new JMenuItem(new AbstractAction("Formatiert") {

        @Override
        public void actionPerformed(ActionEvent e) {
            textArea.append("<%number<formatted='true'>>");
        }
    });
    normal.setToolTipText("Kapitelnummer(1, 2, ...)");
    formatted.setToolTipText("Formatierte Kapitelnummer(001, 002, ...)");
    menu.add(normal);
    menu.add(formatted);
    menu.show(this, getMousePosition().x, getMousePosition().y);
}//GEN-LAST:event_NumberButtonActionPerformed

    /**
     * Adds text to the TextArea to use the filepath
     * @param evt Auto generated event; Not used
     */
private void FilePathButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_FilePathButtonActionPerformed
    textArea.append("<%filepath>");
}//GEN-LAST:event_FilePathButtonActionPerformed

    /**
     * Adds text to the TextArea to use the Filename
     * @param evt Auto generated event; Not used
     */
private void FileNameButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_FileNameButtonActionPerformed
    JPopupMenu menu = new JPopupMenu();
    JMenuItem withExt = new JMenuItem(new AbstractAction("Mit Endung") {

        @Override
        public void actionPerformed(ActionEvent e) {
            textArea.append("<%fileName<showExtention='true'>>");
        }
    });
    JMenuItem withoutExt = new JMenuItem(new AbstractAction("Ohne Endung") {

        @Override
        public void actionPerformed(ActionEvent e) {
            textArea.append("<%fileName<showExtention='false'>>");
        }
    });
    JMenuItem advanced = new JMenuItem(new AbstractAction("Teil des Dateinamens") {

        @Override
        public void actionPerformed(ActionEvent e) {
            MultipleInputPane pane = new MultipleInputPane("Trennungstext", "Index");
            pane.setToolTipText(0, "Bsp: Datei: \"01-Test.m4a\" - Trennungstext: \"-\"");
            pane.setToolTipText(1, "Der Index zwischen den Trennungstexten im Dateinamen. Muss eine Zahl sein(kann mit '#' enden; dann werden alle Teile ab dem Index übernommen)!");
            if (pane.showDialog(null, "Eingabe", JOptionPane.PLAIN_MESSAGE) == JOptionPane.OK_OPTION) {
                textArea.append("<%advancedFileName<sepText='" + pane.getText(0) + "' index='" + pane.getText(1) + "'>>");
            }
        }
    });
    menu.add(withExt);
    menu.add(withoutExt);
    menu.add(advanced);
    menu.show(this, getMousePosition().x, getMousePosition().y);
}//GEN-LAST:event_FileNameButtonActionPerformed

    /**
     * Checks if the file was saved and exits
     * @param evt Auto generated event; Not used
     */
private void CloseMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CloseMenuItemActionPerformed
    if (!isSaved) {
        if (JOptionPane.showConfirmDialog(this, "Die Datei wurde nicht gespeichert. Fenster trotzdem schließen?", "Schließen?", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE) == JOptionPane.NO_OPTION) {
            return;
        }
    }
    dispose();
}//GEN-LAST:event_CloseMenuItemActionPerformed

    /**
     * Opens a JFileChooser Dialog to let the user save the text
     * @param evt 
     */
private void SaveAsMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SaveAsMenuItemActionPerformed
    File userDir = new File(System.getProperty("user.dir"));
    File profileFolder = new File(userDir.getPath() + "/Profile");
    JFileChooser chooser = new JFileChooser(profileFolder.exists() ? profileFolder : userDir);
    chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
    chooser.setMultiSelectionEnabled(false);

    if (chooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
        if (chooser.getSelectedFile().exists() && JOptionPane.showConfirmDialog(this, "Die Datei " + chooser.getSelectedFile().getPath() + " existiert bereits. Überschreiben?", "Überschreiben?", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE) == JOptionPane.NO_OPTION) {
            return;
        }
        try {
            saveFile = chooser.getSelectedFile();
            lastText = textArea.getText();
            FileWriter FWriter = new FileWriter(saveFile);
            BufferedWriter writer = new BufferedWriter(FWriter);

            writer.write(textArea.getText());
            writer.close();
            FWriter.close();
            isSaved = true;
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(this, "Beim Speichern ist ein Fehler aufgetreten.", "Fehler", JOptionPane.ERROR_MESSAGE);
        }
    }
}//GEN-LAST:event_SaveAsMenuItemActionPerformed

    /**
     * Automatically saves the file at the last given file location. If there is no last location this method calls {@link #SaveAsMenuItemActionPerformed(java.awt.event.ActionEvent) SaveAsMenuItemActionPerformed()}
     * @param evt Auto generated event; Not used
     */
private void SaveMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SaveMenuItemActionPerformed
    if (saveFile == null) {
        SaveAsMenuItemActionPerformed(evt);
    } else {
        try {
            lastText = textArea.getText();
            FileWriter FWriter = new FileWriter(saveFile);
            BufferedWriter writer = new BufferedWriter(FWriter);

            writer.write(textArea.getText());
            writer.close();
            FWriter.close();
            isSaved = true;
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(this, "Beim Speichern ist ein Fehler aufgetreten.", "Fehler", JOptionPane.ERROR_MESSAGE);
        }
    }
}//GEN-LAST:event_SaveMenuItemActionPerformed

    /**
     * Checks if the file was saved and exits
     * @param evt Auto generated event; Not used
     */
private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
    CloseMenuItemActionPerformed(null);
}//GEN-LAST:event_formWindowClosing

    /**
     * Adds text to the TextArea to use tags inside the files
     * @param evt Auto generated event; Not used
     */
private void TagButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_TagButtonActionPerformed
    JPopupMenu menu = new JPopupMenu();
    menu.add(new AbstractAction("Titel") {

        @Override
        public void actionPerformed(ActionEvent e) {
            textArea.append("<%tag<id='title'>>");
        }
    });
    menu.add(new AbstractAction("Album") {

        @Override
        public void actionPerformed(ActionEvent e) {
            textArea.append("<%tag<id='album'>>");
        }
    });
    menu.add(new AbstractAction("Interpret") {

        @Override
        public void actionPerformed(ActionEvent e) {
            textArea.append("<%tag<id='artist'>>");
        }
    });
    menu.add(new AbstractAction("Albumsinterpret") {

        @Override
        public void actionPerformed(ActionEvent e) {
            textArea.append("<%tag<id='album_artist'>>");
        }
    });
    menu.add(new AbstractAction("Tracknummer") {

        @Override
        public void actionPerformed(ActionEvent e) {
            textArea.append("<%tag<id='track'>>");
        }
    });
    menu.add(new AbstractAction("Komponist") {

        @Override
        public void actionPerformed(ActionEvent e) {
            textArea.append("<%tag<id='composer'>>");
        }
    });
    menu.show(this, getMousePosition().x, getMousePosition().y);
}//GEN-LAST:event_TagButtonActionPerformed

    /**
     * Adds text to the TextArea to use preview text
     * @param evt Auto generated event; Not used
     */
    private void CommentButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CommentButtonActionPerformed
        textArea.insert("#\n", 0);
    }//GEN-LAST:event_CommentButtonActionPerformed

    /**
     * Lets the user use the typed profile right now in the active project
     * @param evt Auto generated event; Not used
     */
    private void UseNowMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_UseNowMenuItemActionPerformed
        try {
            BufferedReader reader = new BufferedReader(new StringReader(textArea.getText()));
            String profile = "";
            while ((profile = reader.readLine()).startsWith("#")) {
            }
            Main.window.useChapterProfile(profile);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }//GEN-LAST:event_UseNowMenuItemActionPerformed

    /**
     * Lets the user choose a text file to display and edit
     * @param evt 
     */
    private void OpenMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OpenMenuItemActionPerformed
        if (!isSaved) {
            if (JOptionPane.showConfirmDialog(this, "Die Datei wurde nicht gespeichert. Fortfahren?", "Öffnen?", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE) == JOptionPane.NO_OPTION) {
                return;
            }
        }
        File userDir = new File(System.getProperty("user.dir"));
        File profileFolder = new File(userDir.getPath() + "/Profile");
        JFileChooser chooser = new JFileChooser(profileFolder.exists() ? profileFolder : userDir);
        chooser.setMultiSelectionEnabled(false);
        if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
            try {
                textArea.setText("");
                BufferedReader reader = new BufferedReader(new FileReader(chooser.getSelectedFile()));
                String line = "";
                while ((line = reader.readLine()) != null) {
                    textArea.append((textArea.getText().length() < 1 ? "" : "\n") + line);
                }
                isSaved = true;
                saveFile = chooser.getSelectedFile();
                lastText = textArea.getText();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }//GEN-LAST:event_OpenMenuItemActionPerformed
    
    //<editor-fold defaultstate="collapsed" desc="Variables declaration">
    private boolean isSaved = false;
    private File saveFile;
    private String lastText;
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuItem CloseMenuItem;
    private javax.swing.JButton CommentButton;
    private javax.swing.JButton FileNameButton;
    private javax.swing.JButton FilePathButton;
    private javax.swing.JButton NumberButton;
    private javax.swing.JMenuItem OpenMenuItem;
    private javax.swing.JMenuItem SaveAsMenuItem;
    private javax.swing.JMenuItem SaveMenuItem;
    private javax.swing.JButton TagButton;
    private javax.swing.JMenuItem UseNowMenuItem;
    private javax.swing.JPanel addPanel;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JPopupMenu.Separator jSeparator1;
    private javax.swing.JPopupMenu.Separator jSeparator2;
    private javax.swing.JTextArea textArea;
    // End of variables declaration//GEN-END:variables
    //</editor-fold>
}
