/*
 * Copyright (C) 2018 Thomas Almy
 *
 * 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
 * (at your option) 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/>.
 */
package us.almy.jelbum;

import java.util.Iterator;
import java.util.LinkedList;
import javax.swing.UIManager;

/**
 * The Jelbum program
 * @author tom
 */
public class Jelbum extends javax.swing.JFrame {
    JelbumSolver solver;
    /**
     * Creates new form JelbumSolver
     */
    public Jelbum() {
        solver = new JelbumSolver();
        if (!solver.readWords()) System.exit(1); // Failure!
        initComponents();
    }

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

        characterField = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        patternField = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        answerText = new javax.swing.JTextArea();
        solveButton = new javax.swing.JButton();
        clearCharacters = new javax.swing.JButton();
        clearPattern = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Jelbum");

        jLabel1.setText("Characters:");

        jLabel2.setText("Pattern:");

        answerText.setEditable(false);
        answerText.setColumns(20);
        answerText.setRows(5);
        jScrollPane1.setViewportView(answerText);

        solveButton.setText("Solve");
        solveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                solveButtonActionPerformed(evt);
            }
        });

        clearCharacters.setText("Clear");
        clearCharacters.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                clearCharactersActionPerformed(evt);
            }
        });

        clearPattern.setText("Clear");
        clearPattern.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                clearPatternActionPerformed(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(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE)
                        .addGap(14, 14, 14))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(solveButton)
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(characterField)
                            .addComponent(patternField))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(clearCharacters)
                            .addComponent(clearPattern, javax.swing.GroupLayout.Alignment.TRAILING))
                        .addContainerGap())))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(characterField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1)
                    .addComponent(clearCharacters))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel2)
                        .addComponent(patternField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(clearPattern, javax.swing.GroupLayout.Alignment.TRAILING))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 204, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(solveButton)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

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

    private void solveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_solveButtonActionPerformed
        setUpAndSolve();
    }//GEN-LAST:event_solveButtonActionPerformed

    private void clearCharactersActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clearCharactersActionPerformed
        characterField.setText("");
    }//GEN-LAST:event_clearCharactersActionPerformed

    private void clearPatternActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clearPatternActionPerformed
        patternField.setText("");
    }//GEN-LAST:event_clearPatternActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
          try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception ex) {
        }
        ;
        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Jelbum().setVisible(true);
            }
        });
    }
 
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextArea answerText;
    private javax.swing.JTextField characterField;
    private javax.swing.JButton clearCharacters;
    private javax.swing.JButton clearPattern;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField patternField;
    private javax.swing.JButton solveButton;
    // End of variables declaration//GEN-END:variables

    
    private void setUpAndSolve() {
        String text = characterField.getText(); // We want lower case only
        String rawPattern = patternField.getText(); // Spaces versus anything else
        // Arguements for puzzle solver
        LinkedList<Integer> pattern = new LinkedList<>();
        LinkedList<String> answers = new LinkedList<>();
        AWord target = solver.makeAWord(text);
        
        answerText.setText(null);
        
        // Verify valid target
        if (target == null) {
            answerText.setText("Characters must all be lowercase");
            return;
        }
        
        // Create the pattern, converting it to linked lists of lengths
        int count = 0;
        int patternLength = 0;
        for (int i = rawPattern.length()-1; i >= 0; i--) {
            boolean c = rawPattern.charAt(i) != ' ';
            if (c) { // pattern character
                count++;
            } else if (count > 0) {
                pattern.addFirst(count);
                patternLength += count;
                count = 0;
            } else {
                // ignore extra spaces
            }
        }
        if (count > 0) {
            pattern.addFirst(count);
            patternLength += count;
        }
        if (pattern.isEmpty()) { 
            pattern.add(text.length());
            patternLength += text.length();
        }
        if (patternLength > text.length()) {
            answerText.setText("pattern too long");
            return;
        }
        
        // Get the solution
        solver.solve("", pattern, target, answers);
        if (answers.isEmpty()) {
            answerText.setText("No Solution Found");
        } else {
            // Put the solution answers into the answerText field
            Iterator it = answers.iterator();
            while (it.hasNext()) {
                answerText.append((String)it.next());
            }
        }
    }

}