package robotweb;

import java.net.UnknownHostException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLongArray;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.text.DefaultCaret;
import socket.SocketConnexion;

/*
 * Copyright (C) 2016 hux
 *
 * 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/>.
 */
/**
 * Fenetre du programme
 *
 * @author hux
 */
public class windows extends javax.swing.JFrame {

    private static final long serialVersionUID = 1L;

    /**
     * Creates new form windows
     */
    public windows() {
        stop = false;
        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() {

        jRadioButtonMenuItem1 = new javax.swing.JRadioButtonMenuItem();
        jLabel1 = new javax.swing.JLabel();
        input_url_request = new javax.swing.JTextField();
        jButton_Start = new javax.swing.JButton();
        jButton_Stop = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTxtPaneConsole = new javax.swing.JTextPane();
        input_nb_threads = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        input_nb_requetes = new javax.swing.JTextField();
        progressBar = new javax.swing.JProgressBar();
        jLabel5 = new javax.swing.JLabel();
        jLabelIP = new javax.swing.JLabel();
        jTextIP = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        jTextFieldPortClient = new javax.swing.JTextField();
        jScrollPane3 = new javax.swing.JScrollPane();
        jTextPaneConnexion = new javax.swing.JTextPane();
        jButton1 = new javax.swing.JButton();
        jTextFieldPortServeur = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();

        jRadioButtonMenuItem1.setSelected(true);
        jRadioButtonMenuItem1.setText("jRadioButtonMenuItem1");

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setResizable(false);

        jLabel1.setText("Url :");

        input_url_request.setText("http://www.google.com/");
        input_url_request.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                input_url_requestActionPerformed(evt);
            }
        });

        jButton_Start.setText("Start");
        jButton_Start.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_StartActionPerformed(evt);
            }
        });

        jButton_Stop.setText("Stop");
        jButton_Stop.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_StopActionPerformed(evt);
            }
        });

        jScrollPane2.setViewportView(jTxtPaneConsole);
        DefaultCaret caret = (DefaultCaret)jTxtPaneConsole.getCaret();
        caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);

        input_nb_threads.setText("4");
        input_nb_threads.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                input_nb_threadsActionPerformed(evt);
            }
        });

        jLabel2.setText("Nb Threads :");

        jLabel3.setText("Nb Requetes :");

        input_nb_requetes.setText("1");
        input_nb_requetes.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                input_nb_requetesActionPerformed(evt);
            }
        });

        progressBar.setMaximum(17576);
        progressBar.setToolTipText("Progression : ");

        jLabel5.setText("Nb de requêtes faites");

        jLabelIP.setText("IP du client :");

        jTextIP.setText("127.0.0.1");
        jTextIP.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextIPActionPerformed(evt);
            }
        });

        jLabel6.setText("Port du client:");

        jTextFieldPortClient.setText("4024");
        jTextFieldPortClient.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextFieldPortClientActionPerformed(evt);
            }
        });

        jScrollPane3.setViewportView(jTextPaneConnexion);

        jButton1.setText("Start server");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jTextFieldPortServeur.setText("4025");
        jTextFieldPortServeur.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextFieldPortServeurActionPerformed(evt);
            }
        });

        jLabel4.setText("Port du serveur :");

        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()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(6, 6, 6)
                        .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, 201, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton_Stop)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton_Start))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(input_url_request))
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 397, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jLabel2)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(input_nb_threads, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(input_nb_requetes, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(26, 26, 26)))
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jLabelIP)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(jTextIP, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(jLabel6)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(jTextFieldPortClient, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(jLabel4)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(jTextFieldPortServeur, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(jButton1))
                                    .addComponent(jScrollPane3))))))
                .addGap(125, 125, 125))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(input_url_request, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(1, 1, 1)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(input_nb_threads, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2)
                    .addComponent(jLabel3)
                    .addComponent(input_nb_requetes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabelIP)
                    .addComponent(jTextIP, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6)
                    .addComponent(jTextFieldPortClient, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1)
                    .addComponent(jTextFieldPortServeur, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 374, Short.MAX_VALUE)
                    .addComponent(jScrollPane3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jButton_Stop)
                        .addComponent(jButton_Start)))
                .addContainerGap(17, Short.MAX_VALUE))
        );

        setBounds(0, 0, 1018, 515);
    }// </editor-fold>//GEN-END:initComponents

    private void jButton_StartActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_StartActionPerformed
        stop = false;//on réinitialise la variable stop
        //variable à récupérer des champs
        String url = input_url_request.getText();

        String sNb_threads = input_nb_threads.getText();//nombre de thread

        System.out.println(sNb_threads);
        try {
            int nb_threads = Integer.parseInt(sNb_threads);
            nb_request = new AtomicInteger(0);//nb requetes faites
            temps_moyen_threads = new AtomicLongArray(nb_threads);
            debit_moyen_threads = new AtomicLongArray(nb_threads);

            String sNb_requetes = input_nb_requetes.getText();//nombre de requête à faire
            System.out.println(sNb_requetes);
            int nb_requete_a_faire = Integer.parseInt(sNb_requetes);

            //on fixe le maximum de la progress bar pour avoir un affichage correcte de la progression
            progressBar.setMaximum(nb_requete_a_faire);

            //execution de la thread chargé de l'affichage et du lancement des autres threads
            Thread t = new Thread(new thread_print_graphique(nb_requete_a_faire, nb_threads, url));

            t.start();

        } catch (NumberFormatException e) {
            jTxtPaneConsole.setText("Mauvais parmètre(s) renseigné(s)");
        }

    }//GEN-LAST:event_jButton_StartActionPerformed

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

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

    private void jButton_StopActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_StopActionPerformed
        String previous_text_console = windows.jTxtPaneConsole.getText();
        windows.jTxtPaneConsole.setText(previous_text_console + "\n Le serveur c'est arrêté");
        progressBar.setValue(0);
        stop = true;
    }//GEN-LAST:event_jButton_StopActionPerformed

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

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

    //Action qui va déclencher la création d'un server
    //Le server va écouter sur le port passé en paramètre
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        //récupération depuis le formulaire
        ip = jTextIP.getText();
        portServeur = Integer.parseInt(jTextFieldPortServeur.getText());
        portClient = Integer.parseInt(jTextFieldPortClient.getText());
        try {
            SocketConnexion.mainServer(portServeur);
            String previous_text_console = windows.jTextPaneConnexion.getText();
            windows.jTextPaneConnexion.setText(previous_text_console + "\n Serveur démarré correctement");
        } catch (UnknownHostException ex) {
            Logger.getLogger(windows.class.getName()).log(Level.SEVERE, null, ex);
            String previous_text_console = windows.jTxtPaneConsole.getText();
            windows.jTxtPaneConsole.setText(previous_text_console + "\n Le serveur a eu une erreur");
        }
    }//GEN-LAST:event_jButton1ActionPerformed

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

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

    /**
     * @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 ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(windows.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(windows.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(windows.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(windows.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new windows().setVisible(true);
            }
        });

    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField input_nb_requetes;
    private javax.swing.JTextField input_nb_threads;
    private javax.swing.JTextField input_url_request;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton_Start;
    private javax.swing.JButton jButton_Stop;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabelIP;
    private javax.swing.JRadioButtonMenuItem jRadioButtonMenuItem1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTextField jTextFieldPortClient;
    private javax.swing.JTextField jTextFieldPortServeur;
    private javax.swing.JTextField jTextIP;
    public static volatile javax.swing.JTextPane jTextPaneConnexion;
    public static volatile javax.swing.JTextPane jTxtPaneConsole;
    protected static volatile javax.swing.JProgressBar progressBar;
    // End of variables declaration//GEN-END:variables
    //déclaration variable volatile
    //    public static volatile int nb_request = 0;
    //    public static volatile double debit_moyen = 0.0;
    //    public static volatile double temps_moyen = 0.0;

    public static AtomicInteger nb_request;
    public static AtomicLongArray debit_moyen_threads;
    public static AtomicLongArray temps_moyen_threads;
    public static volatile String ip;
    public static volatile int portClient;
    public static volatile int portServeur;
    public static volatile boolean stop;
}
