 /* ALKHALIL MORPHO SYS -- An open source programm.
 *
 * Copyright (C) 2010.
 *
 * This program is free software, distributed under the terms of
 * the GNU General Public License Version 3. For more informations see web site at :
 * http://www.gnu.org/licenses/gpl.txt
 */
package AlKhalil.result;

import AlKhalil.analyse.Analyzer;
import AlKhalil.ui.*;
import AlKhalil.TextIndex;
import java.util.*;
import java.util.prefs.Preferences;
import java.awt.*;
import java.awt.event.*;

/**
 * <p>This class provides implementations to search in the analysis results. it is possible to search by word or by root.
 *
 * </p>
 *
 */
public class SearchResults extends javax.swing.JFrame {

    private static LinkedList<String> strFind = new LinkedList();
    public static int ncoloumns;
    private Preferences prefs;

    /** Creates new form SearchResults */
    public SearchResults() {
        super("بحث في النتائج");
        initComponents();
        RootSearch.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
        jLabel1.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
        TextResult.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
        jScrollPane1.setVisible(false);
        TextResult.setVisible(false);
        //jLabel2.setVisible(false);
        setResizable(false);
        setLayout(null);
        //setSize(554,330);

        prefs = Preferences.userNodeForPackage(this.getClass());
        //prefs.put(, null)

        addWindowListener(new WindowAdapter() {

            public void windowClosing(WindowEvent e) {
                Gui.setting.setEnabled(true);
            }
        });


    }

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

        buttonGroup1 = new javax.swing.ButtonGroup();
        jToggleButton1 = new javax.swing.JToggleButton();
        jToggleButton2 = new javax.swing.JToggleButton();
        jLabel1 = new javax.swing.JLabel();
        RootSearch = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        TextResult = new javax.swing.JEditorPane();
        jButton1 = new javax.swing.JButton();
        jRadioButton1 = new javax.swing.JRadioButton();
        jRadioButton2 = new javax.swing.JRadioButton();
        saveButton = new javax.swing.JToggleButton();

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

        jToggleButton1.setFont(new java.awt.Font("DejaVu Sans", 0, 14)); // NOI18N
        jToggleButton1.setText("بحث");
        jToggleButton1.setMaximumSize(new java.awt.Dimension(200, 41));
        jToggleButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jToggleButton1ActionPerformed(evt);
            }
        });

        jToggleButton2.setFont(new java.awt.Font("DejaVu Sans", 0, 14)); // NOI18N
        jToggleButton2.setText("غلق");
        jToggleButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jToggleButton2ActionPerformed(evt);
            }
        });

        jLabel1.setText(" كلمة البحث");

        RootSearch.setFont(new java.awt.Font("DejaVu Sans", 0, 14));
        RootSearch.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jToggleButton1ActionPerformed(evt);
            }
        });

        TextResult.setContentType("text/html");
        TextResult.setEditable(false);
        TextResult.setFont(new java.awt.Font("DejaVu Sans", 0, 14));
        jScrollPane1.setViewportView(TextResult);

        jButton1.setFont(new java.awt.Font("DejaVu Sans", 0, 14)); // NOI18N
        jButton1.setText("تفريغ الحقول");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        buttonGroup1.add(jRadioButton1);
        jRadioButton1.setFont(new java.awt.Font("DejaVu Sans", 1, 13));
        jRadioButton1.setSelected(true);
        jRadioButton1.setText("بحث بالجذر");
        jRadioButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                hideSaveResults(evt);
            }
        });

        buttonGroup1.add(jRadioButton2);
        jRadioButton2.setFont(new java.awt.Font("DejaVu Sans", 1, 13));
        jRadioButton2.setText("بحث بالكلمة");
        jRadioButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                hideSaveResults(evt);
            }
        });

        saveButton.setFont(new java.awt.Font("DejaVu Sans", 0, 14)); // NOI18N
        saveButton.setText("حفظ النتائج");
        saveButton.setMaximumSize(new java.awt.Dimension(200, 41));
        saveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveButtonActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(156, 156, 156)
                .add(jToggleButton2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 93, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(46, 46, 46)
                .add(jButton1)
                .add(31, 31, 31)
                .add(saveButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 100, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(jToggleButton1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 100, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(204, Short.MAX_VALUE))
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .addContainerGap(159, Short.MAX_VALUE)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jRadioButton1)
                    .add(jRadioButton2))
                .add(123, 123, 123)
                .add(RootSearch, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 299, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(53, 53, 53)
                .add(jLabel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 81, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
            .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 829, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                        .add(jLabel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 45, Short.MAX_VALUE)
                        .add(RootSearch, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 42, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .add(layout.createSequentialGroup()
                        .add(jRadioButton1)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .add(jRadioButton2)))
                .add(18, 18, 18)
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 340, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(18, 18, 18)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jToggleButton2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 27, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jToggleButton1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 32, Short.MAX_VALUE)
                    .add(jButton1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 28, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(saveButton, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 30, Short.MAX_VALUE)))
        );

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

    private void jToggleButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jToggleButton2ActionPerformed

        dispose();
    }//GEN-LAST:event_jToggleButton2ActionPerformed

    private void jToggleButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jToggleButton1ActionPerformed
        String printFind = "";
        TextResult.setContentType("text/html");
        TextResult.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
        TextResult.setEditable(false);

        if (jRadioButton1.isSelected()) {
            printFind = byRootSearch(RootSearch);
        } else {
            printFind = byWordSearch(RootSearch);
        }
        TextResult.setText(printFind);
        jScrollPane1.setVisible(true);
        TextResult.setVisible(true);
    }//GEN-LAST:event_jToggleButton1ActionPerformed

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

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        RootSearch.setText(null);
        jScrollPane1.setVisible(false);
        TextResult.setVisible(false);
        //jLabel2.setVisible(false);
    }//GEN-LAST:event_jButton1ActionPerformed

    private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed
        AlKhalil.result.SaveResults.saveResults(strFind);
    }//GEN-LAST:event_saveButtonActionPerformed

    private void hideSaveResults(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_hideSaveResults
        if (jRadioButton1.isSelected()) {
            saveButton.setVisible(true);
        } else {
            saveButton.setVisible(false);
        }
    }//GEN-LAST:event_hideSaveResults

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField RootSearch;
    private javax.swing.JEditorPane TextResult;
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JRadioButton jRadioButton1;
    private javax.swing.JRadioButton jRadioButton2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JToggleButton jToggleButton1;
    private javax.swing.JToggleButton jToggleButton2;
    private javax.swing.JToggleButton saveButton;
    // End of variables declaration//GEN-END:variables

    //Search by root
    public static String byRootSearch(javax.swing.JTextField RootSearch) {
        HashMap<String, LinkedList> wordInfo = TextIndex.getwordInfo();// Text indexed (word --> positions (line, position in the line) )

        int test = 0;

        strFind.clear();
        LinkedList wordPos = new LinkedList();
        String printFind = "";
        for (int i = 0; i < Analyzer.allResults.size(); i++) {

            HashMap sol = new HashMap();

            sol = Analyzer.allResultsBis.isEmpty() ? (HashMap) Analyzer.allResults.get(i) : (HashMap) Analyzer.allResultsBis.get(i);

            Collection normalizedWords = sol.keySet();
            Iterator itn = normalizedWords.iterator();
            HashMap Lines = new HashMap();

            while (itn.hasNext()) {
                String normalizedWord = (String) itn.next();
                java.util.List result = (java.util.List) sol.get(normalizedWord);
                for (int n = 0; n < result.size(); n++) {
                    String wordRoot = "";
                    Result resul = (Result) result.get(n);
                    wordRoot = resul.getWordroot();
                    Lines.put(wordRoot, "");
                }
                if (Lines.containsKey(RootSearch.getText())) {
                    test++;
                    if (!strFind.contains(normalizedWord)) {
                        strFind.add(normalizedWord);
                    }
                }
            }
        }

        Collections.sort(strFind);


        if (test == 0) {
            printFind = "لا توجد كلمات";
        } else {

            String htmlHead = "<html> <body LANG=\"ar-SA\" DIR=\"LTR\"> <center><font size=3><b>نتائج البحث<br> Search Results</b></font></center><br>\n";
            htmlHead += "";
            htmlHead += "<DIV ALIGN=RIGHT>";
             htmlHead += "<P align=\"right\"> عدد الكلمات:";
        htmlHead += " " + strFind.size() + "</P><BR>";
            htmlHead += "<TABLE DIR=\"RTL\" BORDER=1 CELLSPACING=0>";

            String cellBeg = "<TD align=\"right\">";

            String cellEnd = "</TD>";

            htmlHead += "<TR VALIGN=TOP> ";
            htmlHead += cellBeg + "<B>السياقات</B>" + cellEnd + cellBeg + "<B> مواقع الكلمات  </B>" + cellEnd + cellBeg + "<B>التكرار</B>"
                    + cellEnd + cellBeg + "<B>الكلمة</B>" + cellEnd + "</TR>";


            StringBuffer htmlOutput = new StringBuffer();


            for (int i = 0; i < strFind.size(); i++) {
                String wordFind = strFind.get(i);
                //wordFind = wordFind.replaceAll("[ًٌٍَُِّْ]", "");
                wordPos = wordInfo.get(wordFind);
                htmlOutput.append("<TR VALIGN=TOP> ");
                htmlOutput.append(cellBeg);
                for (int j = 1; j < wordPos.size(); j += 3) {
                    String context = wordPos.get(j).toString() + "<Font color=red> " + strFind.get(i) + " </Font>" + wordPos.get(j + 1).toString() + "<br>";
                    htmlOutput.append(context);
                }
                htmlOutput.append(cellEnd);

                htmlOutput.append(cellBeg);
                for (int j = 0; j < wordPos.size(); j += 3) {
                    String posLine = wordPos.get(j).toString() + "<BR>";
                    htmlOutput.append(posLine);
                }
                htmlOutput.append(cellEnd);

                htmlOutput.append(cellBeg + wordPos.size() / 3 + cellEnd);

                htmlOutput.append(cellBeg + strFind.get(i) + cellEnd);

                htmlOutput.append("</TR>");

            }

            String htmlBottom = "</TABLE> </DIV>"
                    + "</body></html>";

            printFind = htmlHead + htmlOutput.toString() + htmlBottom;
        }

        return printFind;
    }

    //Search by word
    public static String byWordSearch(javax.swing.JTextField RootSearch) {
        HashMap<String, LinkedList> wordInfo = TextIndex.getwordInfo();// Text indexed (word --> (position,left context, right context))
        LinkedList wordPos = new LinkedList();
        String printFind = "";
        String str = RootSearch.getText();
        LinkedList<String> wordDupli = TextIndex.getnormalizedWords();
        if (wordDupli.contains(str)) {
            String htmlHead = "<html> <body LANG=\"ar-SA\" DIR=\"LTR\"> <center><font size=3><b>نتائج البحث<br> Search Results</b></font></center><br>\n";
            htmlHead += "";
            htmlHead += "<DIV ALIGN=RIGHT>";
            htmlHead += "<TABLE DIR=\"RTL\" BORDER=1 CELLSPACING=0>";

            String cellBeg = "<TD align=\"right\">";

            String cellEnd = "</TD>";

            htmlHead += "<TR VALIGN=TOP> ";
            htmlHead += cellBeg + "<B>السياقات</B>" + cellEnd + cellBeg + "<B> مواقع الكلمات  </B>" + cellEnd + cellBeg + "<B>التكرار</B>"
                    + cellEnd + cellBeg + "<B>الكلمة</B>" + cellEnd + "</TR>";


            StringBuffer htmlOutput = new StringBuffer();
            //String wordFind = str.replaceAll("[ًٌٍَُِّْ]", "");
            wordPos = wordInfo.get(str);
            htmlOutput.append("<TR VALIGN=TOP> ");
            htmlOutput.append(cellBeg);
            for (int j = 1; j < wordPos.size(); j += 3) {
                String context = wordPos.get(j).toString() + "<Font color=red> " + str + " </Font>" + wordPos.get(j + 1).toString() + "<br>";
                htmlOutput.append(context);
            }
            htmlOutput.append(cellEnd);

            htmlOutput.append(cellBeg);
            for (int j = 0; j < wordPos.size(); j += 3) {
                String posLine = wordPos.get(j).toString();
                htmlOutput.append(posLine + "<BR>");
            }
            htmlOutput.append(cellEnd);

            htmlOutput.append(cellBeg + wordPos.size() / 3 + cellEnd);

            htmlOutput.append(cellBeg + str + cellEnd);

            htmlOutput.append("</TR>");



            String htmlBottom = "</TABLE> </DIV>"
                    + "</body></html>";

            printFind = htmlHead + htmlOutput.toString() + htmlBottom;
        } else {
            printFind = "لا توجد كلمات";
        }

        return printFind;
    }
}
