<filename>src/views/SourceCodeEditor.java
package views;

import controllers.LoadFile;
import java.io.File;
import java.util.List;
import javax.swing.JFileChooser;
import static javax.swing.JFileChooser.APPROVE_OPTION;
import static javax.swing.JFileChooser.CANCEL_OPTION;
import static javax.swing.JFileChooser.OPEN_DIALOG;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.DefaultTableModel;
import lexical.Analyzer;
import models.TextAreaBorder;
import models.Token;

/**
 *
 * @author CarlosMacaneta
 */
public class SourceCodeEditor extends javax.swing.JFrame {

    /**
     * Creates new form SourceCoderEditor
     */
    public SourceCodeEditor() {
        initComponents();
        manageEditor();
    }

    private void manageEditor() {
       codeEditor.setBorder(new TextAreaBorder());
    }
    
    private void openFile() {
        JFileChooser jFile = new JFileChooser(System.getProperty("user.dir"));
        
        FileNameExtensionFilter filter = new FileNameExtensionFilter("*.pas", "pas");
        
        jFile.addChoosableFileFilter(filter);
        jFile.setAcceptAllFileFilterUsed(false);
        
        jFile.setDialogType(OPEN_DIALOG); 
        
        int result = jFile.showOpenDialog(this);
        
        if(result == APPROVE_OPTION){
            File selectedFile = jFile.getSelectedFile();
            String path = selectedFile.getAbsolutePath();
            
            if(path.toLowerCase().endsWith("pas")) {
                LoadFile lf = new LoadFile();
                
                codeEditor.setText(lf.load(path).toString());
            }else{ 
                JOptionPane.showMessageDialog(this, "Ficheiro não suportado.\nSelecione"
                        + " ficheiro com o seguinte formato pas", "WARNING MESSAGE",JOptionPane.WARNING_MESSAGE);
            }
        }else if(result == CANCEL_OPTION){ System.out.println("CANCELED"); }
    }
    

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

        jMenuItem1 = new javax.swing.JMenuItem();
        jMenuItem2 = new javax.swing.JMenuItem();
        main = new javax.swing.JPanel();
        toolBar = new javax.swing.JToolBar();
        jButton4 = new javax.swing.JButton();
        internalToolBar1 = new javax.swing.JToolBar();
        internalToolBar2 = new javax.swing.JToolBar();
        jButton2 = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        btnRun = new javax.swing.JButton();
        sideBar = new javax.swing.JPanel();
        jPanel3 = new javax.swing.JPanel();
        tabbedPaneEditorContainer = new javax.swing.JTabbedPane();
        start = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        codeEditor = new javax.swing.JTextArea();
        outputPane = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        tokenClass = new javax.swing.JTable();
        bugArea = new javax.swing.JPanel();
        jScrollPane3 = new javax.swing.JScrollPane();
        bugText = new javax.swing.JTextArea();
        jLabel1 = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        topBar = new javax.swing.JMenuBar();
        file = new javax.swing.JMenu();
        newProject = new javax.swing.JMenuItem();
        newFile = new javax.swing.JMenuItem();
        jSeparator1 = new javax.swing.JPopupMenu.Separator();
        openProject = new javax.swing.JMenuItem();
        edit = new javax.swing.JMenu();

        jMenuItem1.setText("jMenuItem1");

        jMenuItem2.setText("jMenuItem2");

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

        main.setBackground(new java.awt.Color(255, 255, 255));
        main.setLayout(new java.awt.BorderLayout());

        toolBar.setMargin(new java.awt.Insets(5, 5, 5, 5));

        jButton4.setFont(new java.awt.Font("Segoe UI", 0, 12)); // NOI18N
        jButton4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/icons8_file_24px_2.png"))); // NOI18N
        jButton4.setText("Open file");
        jButton4.setFocusable(false);
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });
        toolBar.add(jButton4);

        internalToolBar1.setRollover(true);
        toolBar.add(internalToolBar1);

        internalToolBar2.setRollover(true);

        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/icons8_undo_24px.png"))); // NOI18N
        jButton2.setFocusable(false);
        jButton2.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton2.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        internalToolBar2.add(jButton2);

        toolBar.add(internalToolBar2);

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/icons8_redo_24px.png"))); // NOI18N
        jButton1.setFocusable(false);
        jButton1.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton1.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        toolBar.add(jButton1);

        jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/icons8_broom_24px.png"))); // NOI18N
        jButton3.setToolTipText("Limpar output");
        jButton3.setFocusable(false);
        jButton3.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton3.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });
        toolBar.add(jButton3);

        btnRun.setFont(new java.awt.Font("Segoe UI", 0, 12)); // NOI18N
        btnRun.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/icons8_play_24px_7.png"))); // NOI18N
        btnRun.setToolTipText("Run");
        btnRun.setFocusable(false);
        btnRun.setHorizontalAlignment(javax.swing.SwingConstants.LEADING);
        btnRun.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btnRun.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnRun.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRunActionPerformed(evt);
            }
        });
        toolBar.add(btnRun);

        main.add(toolBar, java.awt.BorderLayout.PAGE_START);

        sideBar.setLayout(new java.awt.BorderLayout());
        sideBar.add(jPanel3, java.awt.BorderLayout.CENTER);

        main.add(sideBar, java.awt.BorderLayout.LINE_START);

        tabbedPaneEditorContainer.setToolTipText("");

        start.setBackground(new java.awt.Color(255, 255, 255));
        start.setFocusable(false);
        start.setLayout(new java.awt.BorderLayout());

        codeEditor.setColumns(20);
        codeEditor.setFont(new java.awt.Font("Consolas", 0, 14)); // NOI18N
        codeEditor.setLineWrap(true);
        codeEditor.setRows(5);
        codeEditor.setTabSize(4);
        jScrollPane1.setViewportView(codeEditor);

        start.add(jScrollPane1, java.awt.BorderLayout.CENTER);

        tabbedPaneEditorContainer.addTab("Editor", start);

        main.add(tabbedPaneEditorContainer, java.awt.BorderLayout.CENTER);

        outputPane.setMinimumSize(new java.awt.Dimension(889, 250));
        outputPane.setPreferredSize(new java.awt.Dimension(889, 250));
        outputPane.setLayout(new java.awt.BorderLayout());

        tokenClass.setFont(new java.awt.Font("Segoe UI", 0, 12)); // NOI18N
        tokenClass.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Token", "Classe", "Linha"
            }
        ));
        tokenClass.setRowHeight(20);
        tokenClass.setRowMargin(5);
        jScrollPane2.setViewportView(tokenClass);

        outputPane.add(jScrollPane2, java.awt.BorderLayout.CENTER);

        bugText.setEditable(false);
        bugText.setColumns(20);
        bugText.setFont(new java.awt.Font("Consolas", 0, 14)); // NOI18N
        bugText.setForeground(new java.awt.Color(204, 0, 0));
        bugText.setLineWrap(true);
        bugText.setRows(5);
        bugText.setTabSize(4);
        jScrollPane3.setViewportView(bugText);

        jLabel1.setFont(new java.awt.Font("Segoe UI", 0, 12)); // NOI18N
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("<NAME>");
        jLabel1.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED, java.awt.Color.white, new java.awt.Color(255, 255, 255), java.awt.Color.lightGray, java.awt.Color.lightGray));

        javax.swing.GroupLayout bugAreaLayout = new javax.swing.GroupLayout(bugArea);
        bugArea.setLayout(bugAreaLayout);
        bugAreaLayout.setHorizontalGroup(
            bugAreaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 240, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 240, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        bugAreaLayout.setVerticalGroup(
            bugAreaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(bugAreaLayout.createSequentialGroup()
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, 0)
                .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 210, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        outputPane.add(bugArea, java.awt.BorderLayout.LINE_END);
        outputPane.add(jPanel1, java.awt.BorderLayout.LINE_START);

        jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/icons8_output_16px.png"))); // NOI18N
        jLabel3.setText("Output");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel3)
                .addContainerGap(825, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
        );

        outputPane.add(jPanel2, java.awt.BorderLayout.PAGE_START);

        main.add(outputPane, java.awt.BorderLayout.PAGE_END);

        getContentPane().add(main, java.awt.BorderLayout.CENTER);

        file.setText("File");

        newProject.setText("New Project");
        newProject.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                newProjectActionPerformed(evt);
            }
        });
        file.add(newProject);

        newFile.setText("New File");
        file.add(newFile);
        file.add(jSeparator1);

        openProject.setText("Open Project");
        openProject.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                openProjectActionPerformed(evt);
            }
        });
        file.add(openProject);

        topBar.add(file);

        edit.setText("Edit");
        topBar.add(edit);

        setJMenuBar(topBar);

        setSize(new java.awt.Dimension(905, 542));
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void newProjectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newProjectActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_newProjectActionPerformed

    private void btnRunActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRunActionPerformed
        if (!codeEditor.getText().isEmpty()) {
            catchCode();
            seekUndefined();
        }
    }//GEN-LAST:event_btnRunActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        bugText.setText(null);
        DefaultTableModel tableModel = (DefaultTableModel) tokenClass.getModel();
        tableModel.setNumRows(0);
    }//GEN-LAST:event_jButton3ActionPerformed

    private void openProjectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_openProjectActionPerformed
        openFile();
    }//GEN-LAST:event_openProjectActionPerformed

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
       openFile();
    }//GEN-LAST:event_jButton4ActionPerformed

    
    private void catchCode() {
        DefaultTableModel tableModel = (DefaultTableModel) tokenClass.getModel();
        tableModel.setNumRows(0);
        Analyzer analyser = new Analyzer();
        final String[] splitedLines = codeEditor.getText().split("\n");
        int row = -1;
        int pos = 0;
        
        List<String> codeLines = analyser.scan(splitedLines);
        
        for(String line: codeLines) {
            
            for (int i = 0; i < splitedLines.length; i++) {
            
                if (splitedLines[i].contains(line) && !splitedLines[i].isEmpty()) {
                    if (line.equals(";")) { row = Integer.parseInt(String.valueOf(tableModel.getValueAt(tableModel.getRowCount()-1, 2))); }
                    
                    Token token = new Token(line, analyser.getTokenType(line), row == -1 ? i+1 : row++, pos+1);
                    
                    tableModel.addRow(new String[]{
                        token.getValue(),
                        token.getType().getTYPE(),
                        String.valueOf(token.getRow())
                    });
                    row = -1;
                    break;
                }
            }
        }
    }
    
    private void seekUndefined() {
        StringBuilder numLine = new StringBuilder();
        for(int i = 0; i < tokenClass.getRowCount(); i++) {
            if (String.valueOf(tokenClass.getValueAt(i, 1)).equalsIgnoreCase("Undefined"))
                numLine.append(String.valueOf(tokenClass.getValueAt(i, 2))).append(", ");
        }
        bugText.setText("Undefined tokens was found. \nLines: "+ numLine);
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Windows".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(SourceCodeEditor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(SourceCodeEditor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(SourceCodeEditor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(SourceCodeEditor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        //</editor-fold>
        //</editor-fold>
        //</editor-fold>
        //</editor-fold>
        //</editor-fold>
        //</editor-fold>
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(() -> {
            new SourceCodeEditor().setVisible(true);
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnRun;
    private javax.swing.JPanel bugArea;
    private javax.swing.JTextArea bugText;
    private javax.swing.JTextArea codeEditor;
    private javax.swing.JMenu edit;
    private javax.swing.JMenu file;
    private javax.swing.JToolBar internalToolBar1;
    private javax.swing.JToolBar internalToolBar2;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JPopupMenu.Separator jSeparator1;
    private javax.swing.JPanel main;
    private javax.swing.JMenuItem newFile;
    private javax.swing.JMenuItem newProject;
    private javax.swing.JMenuItem openProject;
    private javax.swing.JPanel outputPane;
    private javax.swing.JPanel sideBar;
    private javax.swing.JPanel start;
    private javax.swing.JTabbedPane tabbedPaneEditorContainer;
    private javax.swing.JTable tokenClass;
    private javax.swing.JToolBar toolBar;
    private javax.swing.JMenuBar topBar;
    // End of variables declaration//GEN-END:variables
}
