text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package pts2soutenancemanager.Interface.SaisirVoeux;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import pts2soutenancemanager.Interface.Application;
import pts2soutenancemanager.Database.Tools.ButtonTable;

/**
 *
 * @author minhh
 */
public class SV_EtudiantSaisirDemande extends javax.swing.JFrame {

    Application app;
    ArrayList<Integer> b_listeEtudiantS2 = new ArrayList<>();
    ArrayList<Integer> b_listeEtudiantS4 = new ArrayList<>();
    int idEtudiantS2;

    /**
     * Creates new form EtudiantSaisirDemande
     * @param app L'application
     */
    public SV_EtudiantSaisirDemande(Application app) {
        this.app = app;
        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() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jScrollPane3 = new javax.swing.JScrollPane();
        listeDesVoeuxS2 = new javax.swing.JTable();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        submenu_Main = new javax.swing.JButton();
        jScrollPane5 = new javax.swing.JScrollPane();
        VoeuxEtudiantS2Table = new javax.swing.JTable();
        button_EnvoyerDemande = new javax.swing.JButton();
        listeGroupe = new javax.swing.JComboBox<>();
        listeEtudiantS2 = new javax.swing.JComboBox<>();
        listeParcours = new javax.swing.JComboBox<>();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setMinimumSize(new java.awt.Dimension(946, 586));

        jLabel1.setFont(new java.awt.Font("Segoe UI", 1, 14)); // NOI18N
        jLabel1.setText("Sélectionner un étudiant");

        jLabel2.setText("Choisir un groupe");

        jLabel3.setText("Choisir votre nom");

        jLabel4.setText("Liste des vœux de l'étudiant sélectionné");

        listeDesVoeuxS2.setAutoCreateRowSorter(true);
        jScrollPane3.setViewportView(listeDesVoeuxS2);

        jLabel5.setText("Ajouter un vœu");

        jLabel6.setText("Choisir le parcours");

        submenu_Main.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pts2soutenancemanager/Interface/ui/button/ui_bt_return_main.png"))); // NOI18N
        submenu_Main.setText("Accueil");
        submenu_Main.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                submenu_MainActionPerformed(evt);
            }
        });

        VoeuxEtudiantS2Table.setAutoCreateRowSorter(true);
        jScrollPane5.setViewportView(VoeuxEtudiantS2Table);

        button_EnvoyerDemande.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pts2soutenancemanager/Interface/ui/button/ui_bt_envoyer.png"))); // NOI18N
        button_EnvoyerDemande.setText("Envoyer les demandes");
        button_EnvoyerDemande.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                button_EnvoyerDemandeActionPerformed(evt);
            }
        });

        listeGroupe.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                listeGroupeActionPerformed(evt);
            }
        });

        listeEtudiantS2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                listeEtudiantS2ActionPerformed(evt);
            }
        });

        ArrayList<String> itemList = new ArrayList<>();
        b_listeEtudiantS4.clear();
        try{
            ResultSet result1 = app.util_MySQL.get_db_query("select distinct E4.parcours from `etudiant_s4` E4 ORDER BY 1");
            while(result1.next()){
                itemList.add(result1.getString("parcours"));
            }
            result1.close();
        }
        catch(SQLException e){
            System.out.println("SQLTools: error");
        }
        listeParcours.setModel(new javax.swing.DefaultComboBoxModel<>(itemList.toArray(new String[itemList.size()])));
        listeParcours.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                listeParcoursActionPerformed(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()
                .addGap(66, 66, 66)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(submenu_Main)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(jLabel2)
                                    .addComponent(jLabel1)
                                    .addComponent(jLabel3)
                                    .addComponent(listeGroupe, 0, 188, Short.MAX_VALUE)
                                    .addComponent(listeEtudiantS2, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                .addGap(76, 76, 76)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 554, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jLabel4)))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel5)
                                .addGap(106, 106, 106)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel6)
                                    .addComponent(listeParcours, javax.swing.GroupLayout.PREFERRED_SIZE, 173, javax.swing.GroupLayout.PREFERRED_SIZE))))
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(button_EnvoyerDemande)
                            .addComponent(jScrollPane5, javax.swing.GroupLayout.PREFERRED_SIZE, 818, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(0, 62, Short.MAX_VALUE))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(submenu_Main)
                        .addGap(22, 22, 22)
                        .addComponent(jLabel1)
                        .addGap(18, 18, 18)
                        .addComponent(jLabel2)
                        .addGap(4, 4, 4)
                        .addComponent(listeGroupe, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(25, 25, 25)
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(listeEtudiantS2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(5, 5, 5))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 132, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(18, 18, 18)
                .addComponent(jLabel6)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(listeParcours, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane5, javax.swing.GroupLayout.DEFAULT_SIZE, 223, Short.MAX_VALUE)
                .addGap(26, 26, 26)
                .addComponent(button_EnvoyerDemande)
                .addGap(25, 25, 25))
        );

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

    /**
     * Afficher le menu {@link pts2soutenancemanager.Interface.Main}
     * @param evt le clic du souris
     */
    private void submenu_MainActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_submenu_MainActionPerformed
        // TODO add your handling code here:
        this.app.showMenu(app.menu_mainMenu);
        Application.hideMenu(this);
    }//GEN-LAST:event_submenu_MainActionPerformed

    /**
     * Parcourir la table {@link #VoeuxEtudiantS2Table} et envoyer les voeux valdees (cochees) vers la BD
     * @param evt le clic de souris
     */
    private void button_EnvoyerDemandeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_button_EnvoyerDemandeActionPerformed
        try {
            // TODO add your handling code here:
            JTable target = this.VoeuxEtudiantS2Table;
            int row = target.getRowCount();

            int nbVoeu = 0;
            ResultSet result = app.util_MySQL.get_db_query("SELECT COUNT(*) FROM `voeu` WHERE `id_etu_s2` = "+ Integer.toString(idEtudiantS2) +"");
            while(result.next()){
                nbVoeu = result.getInt(1);
            }

            for(int i = 0; i < row; i++){
                boolean confirm = (boolean) target.getModel().getValueAt(i, 6);
                if( confirm && nbVoeu < 4 ){
                    int idSoutenance = (int) target.getModel().getValueAt(i, 0);
                    String query = "INSERT INTO `voeu`(`id_voeu`, `id_etu_s2`, `id_soutenance`) VALUES ((SELECT IFNULL((SELECT V.id_voeu FROM `voeu` V WHERE V.id_etu_s2 = '" + Integer.toString(this.idEtudiantS2) + "' and V.id_soutenance = '" + Integer.toString(idSoutenance) + "'), (select count(*) from `voeu` V1))), '" + Integer.toString(this.idEtudiantS2) + "', '" + Integer.toString(idSoutenance) + "') ON DUPLICATE KEY UPDATE `id_etu_s2` = '" + Integer.toString(this.idEtudiantS2) + "', `id_soutenance` = '" + Integer.toString(idSoutenance) + "'";
                    this.app.util_MySQL.set_db_field(query);
                    nbVoeu++;
                }
                /*else {
                    JOptionPane.showMessageDialog(this,
                            "Nombre de voeux maximum atteint.",
                            "Attention",
                            JOptionPane.INFORMATION_MESSAGE,
                            new javax.swing.ImageIcon(getClass().getResource("/pts2soutenancemanager/Interface/ui/button/ui_info.png")));
                    break;
                }*/
            }

            this.refreshTableListeVoeuxS2();
        } catch (SQLException ex) {
            Logger.getLogger(SV_EtudiantSaisirDemande.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_button_EnvoyerDemandeActionPerformed

    private void listeGroupeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_listeGroupeActionPerformed
        // TODO add your handling code here:
        JComboBox theList = (JComboBox) evt.getSource();
        int index = theList.getSelectedIndex();
        if (index >= 0) {
            Object o = theList.getModel().getElementAt(index);
            //System.out.println("Double-clicked on: " + o.toString());

            //Update list
            ArrayList<String> itemList = new ArrayList<>();
            this.b_listeEtudiantS2.clear();
            try {
                try (ResultSet result = app.util_MySQL.get_db_query("select * from `etudiant_s2` where `groupe` = '" + o.toString() + "'")) {
                    while (result.next()) {
                        itemList.add(result.getString("nom") + " " + result.getString("Prenom"));
                        b_listeEtudiantS2.add(result.getInt("id_etu_s2"));
                    }
                }
            } catch (SQLException e) {
                System.out.println("SQLTools: error");
            }

            String[] strings = itemList.toArray(new String[itemList.size()]);
            listeEtudiantS2.setModel(new javax.swing.DefaultComboBoxModel<>(strings));
        }
    }//GEN-LAST:event_listeGroupeActionPerformed

    private void listeEtudiantS2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_listeEtudiantS2ActionPerformed
        // TODO add your handling code here:
        JComboBox theList = (JComboBox) evt.getSource();
        int index = theList.getSelectedIndex();
        if (index >= 0) {
            Object o = theList.getModel().getElementAt(index);
            idEtudiantS2 = this.b_listeEtudiantS2.get(index);
            this.refreshTableListeVoeuxS2();
        }
    }//GEN-LAST:event_listeEtudiantS2ActionPerformed

    private void listeParcoursActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_listeParcoursActionPerformed
        // TODO add your handling code here:
        JComboBox theList = (JComboBox) evt.getSource();
        int index = theList.getSelectedIndex();
        if (index >= 0) {
            Object o = theList.getModel().getElementAt(index);

            ArrayList<Object[]> itemList = new ArrayList<>();
            try {
                String query = "SELECT distinct SO.id_soutenance, E4.nom, E4.Prenom,SO.jour, SO.heure_debut, ST.theme, ST.nom_entreprise FROM `etudiant_s4`E4, `soutenance` SO, `stage` ST WHERE E4.parcours = '" + o.toString() + "' and SO.id_etu_s4 = E4.id_etu_s4 and E4.id_etu_s4 = ST.id_etu_s4";
                try (ResultSet result0 = app.util_MySQL.get_db_query(query)) {
                    while (result0 != null && result0.next()) {
                        ArrayList<Object> itemSubList = new ArrayList<>();

                        itemSubList.add(result0.getInt(1));
                        itemSubList.add(result0.getString(2) + " " + result0.getString(3));
                        itemSubList.add(result0.getString(7));
                        itemSubList.add(result0.getString(4));
                        itemSubList.add(result0.getString(5));
                        itemSubList.add(result0.getString(6));
                        itemSubList.add(new Boolean(false));

                        itemList.add(itemSubList.toArray(new Object[itemSubList.size()]));

                    }
                }
            } catch (SQLException e) {
                System.out.println("SQLTools: error. Check sql queries.");
            }
            VoeuxEtudiantS2Table.setModel(new javax.swing.table.DefaultTableModel(
                    itemList.toArray(new Object[itemList.size()][7]),
                    new String[]{
                        "Soutenance", "EtudiantS4", "Entreprise", "Date Passage", "Horaire Passage", "Sujet", "Ajouter aux voeux"
                    }
            ) {
                Class[] types = new Class[]{
                    java.lang.Integer.class,
                    java.lang.String.class,
                    java.lang.String.class,
                    java.lang.String.class,
                    java.lang.String.class,
                    java.lang.String.class,
                    java.lang.Boolean.class
                };
                boolean[] canEdit = new boolean[]{
                    false, false, false, false, false, false, true
                };

                public Class getColumnClass(int columnIndex) {
                    return types[columnIndex];
                }

                public boolean isCellEditable(int rowIndex, int columnIndex) {
                    return canEdit[columnIndex];
                }
            });
        }
    }//GEN-LAST:event_listeParcoursActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTable VoeuxEtudiantS2Table;
    private javax.swing.JButton button_EnvoyerDemande;
    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.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane5;
    private javax.swing.JTable listeDesVoeuxS2;
    private javax.swing.JComboBox<String> listeEtudiantS2;
    private javax.swing.JComboBox<String> listeGroupe;
    private javax.swing.JComboBox<String> listeParcours;
    private javax.swing.JButton submenu_Main;
    // End of variables declaration//GEN-END:variables

    /**
     * Rafraichir le contenu de la table {@link #listeDesVoeuxS2}
     */
    public void refreshTableListeVoeuxS2() {
        //Update table
        ArrayList<Object[]> itemList = new ArrayList<>();
        try {
            String query = "select distinct V.id_soutenance, E4.nom, E4.Prenom, E4.parcours, S.jour, S.heure_debut, ST.nom_entreprise from `voeu` V, `etudiant_s2` E2, `soutenance` S, `etudiant_s4` E4, `stage` ST where V.id_etu_s2 = " + Integer.toString(idEtudiantS2) + " and V.id_etu_s2 = E2.id_etu_s2 and V.id_soutenance = S.id_soutenance and S.id_etu_s4 = E4.id_etu_s4 and ST.id_etu_S4 = E4.id_etu_s4";
            try (ResultSet result = app.util_MySQL.get_db_query(query)) {
                while (result.next()) {
                    ArrayList<Object> itemSubList = new ArrayList<>();

                    itemSubList.add(result.getInt(1));
                    itemSubList.add(result.getString(2) + " " + result.getString(3));
                    itemSubList.add(result.getString(7));
                    itemSubList.add(result.getString(4));
                    itemSubList.add(result.getString(5));
                    itemSubList.add(result.getString(6));
                    itemSubList.add( new JButton() );
                    itemSubList.add( new JButton() );

                    itemList.add(itemSubList.toArray(new Object[itemSubList.size()]));

                }
            }
        } catch (SQLException e) {
            System.out.println("SQLTools: error. Check sql queries.");
        }

        listeDesVoeuxS2.setModel(new javax.swing.table.DefaultTableModel(
                itemList.toArray(new Object[itemList.size()][8]),
                new String[]{
                    "Soutenance", "Etudiant S4", "Entreprise", "Parcours", "Date passage", "Horaire passage", "Sujet", "Supprimer"
                }
        ) {
            Class[] types = new Class[]{
                java.lang.Integer.class,
                java.lang.String.class,
                java.lang.String.class,
                java.lang.String.class,
                java.lang.String.class,
                java.lang.String.class,
                javax.swing.JButton.class,
                javax.swing.JButton.class
            };

            boolean[] canEdit = new boolean[]{
                false, false, false, false, false, false, true, true
            };

            @Override
            public Class getColumnClass(int columnIndex) {
                return types[columnIndex];
            }

            @Override
            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit[columnIndex];
            }
        });

        listeDesVoeuxS2.setRowHeight(30);
        ButtonTableSujet bTableSujet = new ButtonTableSujet(listeDesVoeuxS2, app);
        ButtonTableDelete bTableDelete = new ButtonTableDelete(listeDesVoeuxS2, app);

        listeDesVoeuxS2.getColumnModel().getColumn(6).setCellEditor(bTableSujet);
        listeDesVoeuxS2.getColumnModel().getColumn(6).setCellRenderer(bTableSujet);

        listeDesVoeuxS2.getColumnModel().getColumn(7).setCellEditor(bTableDelete);
        listeDesVoeuxS2.getColumnModel().getColumn(7).setCellRenderer(bTableDelete);

        listeDesVoeuxS2.getColumnModel().getColumn(0).setMaxWidth(30);

        DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
        centerRenderer.setHorizontalAlignment(JLabel.CENTER);
        listeDesVoeuxS2.setDefaultRenderer(Object.class, centerRenderer);
        jScrollPane3.setViewportView(listeDesVoeuxS2);
    }

    /**
     * Appeler le renderer du tableau pour rendre les boutons. Voir {@link pts2soutenancemanager.Database.Tools.ButtonTable}
     */
    public class ButtonTableSujet extends ButtonTable {

         public ButtonTableSujet(JTable ListeEtudiantS2, Application app) {
            super(ListeEtudiantS2, app);
        }

        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            AbstractAction action = new AbstractAction() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    int row = table.getSelectedRow();
                    int idSoutenance = (int) table.getModel().getValueAt(row, 0);
                    try {
                        String query = "select E4.nom, E4.Prenom, SO.jour, SO.heure_debut, ST.theme from `etudiant_s4` E4, `soutenance` SO, `stage` ST where SO.id_soutenance = " + Integer.toString(idSoutenance) + " and E4.id_etu_s4 = SO.id_etu_s4 and SO.id_etu_S4 = ST.id_etu_s4";
                        //System.out.println(query);
                        ResultSet result0 = app.util_MySQL.get_db_query(query);
                        if (result0 != null) {
                            while (result0.next()) {
                                // Announce a message
                                JOptionPane.showMessageDialog(app.menu_EtudiantSaisirDemande,
                                        "Soutenance de " + result0.getString("nom") + " " + result0.getString("Prenom") + " le " + result0.getString("jour") + " à " + result0.getString("heure_debut") + ": "
                                        +textToParagraph("\n" + result0.getString("theme")),
                                        "Information de la soutenance "+Integer.toString(idSoutenance)+"",
                                        JOptionPane.INFORMATION_MESSAGE,
                                        new javax.swing.ImageIcon(getClass().getResource("/pts2soutenancemanager/Interface/ui/button/ui_info.png")));
                            }
                            result0.close();
                        }
                    } catch (SQLException ex) {
                        System.out.println("SQLError");
                    }
                }
            };
            JButton button1 = new JButton(action);
            button1.setText("Voir...");

            JPanel panel = new JPanel();
            panel.add(button1);

            panel.setBackground(table.getBackground());
            return panel;
        }
    }

    /**
     * Transformer une ligne de texte en un paragraphe
     * @param text Une ligne de texte
     * @return Un paragraphe
     */
    public String textToParagraph(String text){
        String result = "";
        String pattern = ".\\?";
        String[] par = text.split(String.format(pattern, "."));
        for(int i = 0; i < par.length;i++){
            result+=par[i]+"\n";
        }
        return result;
    }

    /**
     * Rafraichir le contenu de la liste des groupes
     */
    public void listeGroupeRefreshContent() {
        ArrayList<String> itemList = new ArrayList<>();
        try {
            try (ResultSet result = app.util_MySQL.get_db_query("select distinct `groupe` from `etudiant_s2`")) {
                while (result.next()) {
                    itemList.add(result.getString(1));
                }
            }
        } catch (SQLException e) {
            System.out.println("SQLTools: error");
        }
        String[] strings = itemList.toArray(new String[itemList.size()]);
        listeGroupe.setModel(new javax.swing.DefaultComboBoxModel<>(strings));
    }

    /**
     * Appeler le renderer du tableau pour rendre les boutons. Voir {@link pts2soutenancemanager.Database.Tools.ButtonTable}
     */
    public class ButtonTableDelete extends ButtonTable{

        public ButtonTableDelete(JTable table, Application app) {
            super(table, app);
        }

        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            AbstractAction action = new AbstractAction() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    //System.out.print("Clicked");
                    app.util_MySQL.delete_db_field("voeu", "id_etu_s2 = "+ Integer.toString(idEtudiantS2) +" and id_soutenance = " + Integer.toString((int) table.getModel().getValueAt(table.getSelectedRow(), 0)) + "");
                    app.menu_EtudiantSaisirDemande.refreshTableListeVoeuxS2();
                }
            };
            JButton button1 = new JButton(action);
            button1.setText("Supprimer");

            JPanel panel = new JPanel();
            panel.add(button1);

            panel.setBackground(table.getBackground());
            return panel;
        }

    }
}


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
var PIVOT_PREFIX = exports.PIVOT_PREFIX = '_pivot_';

redpajama_set_name: RedPajamaGithub


text:
#ifndef RTE_COMPONENTS_H
#define RTE_COMPONENTS_H

#if defined(ARMCM0)
#define CMSIS_device_header "ARMCM0.h"
#elif defined(ARMCM0P)
#define CMSIS_device_header "ARMCM0plus.h"
#elif defined(ARMCM0P_MPU)
#define CMSIS_device_header "ARMCM0plus_MPU.h"
#elif defined(ARMCM3)
#define CMSIS_device_header "ARMCM3.h"
#elif defined(ARMCM4)
#define CMSIS_device_header "ARMCM4.h"
#elif defined(ARMCM4_FP)
#define CMSIS_device_header "ARMCM4_FP.h"
#elif defined(ARMCM7)
#define CMSIS_device_header "ARMCM7.h"
#elif defined(ARMCM7_SP)
#define CMSIS_device_header "ARMCM7_SP.h"
#elif defined(ARMCM7_DP)
#define CMSIS_device_header "ARMCM7_DP.h"
#elif defined(ARMCM23)
#define CMSIS_device_header "ARMCM23.h"
#elif defined(ARMCM23_TZ)
#define CMSIS_device_header "ARMCM23_TZ.h"
#elif defined(ARMCM33)
#define CMSIS_device_header "ARMCM33.h"
#elif defined(ARMCM33_DSP_FP)
#define CMSIS_device_header "ARMCM33_DSP_FP.h"
#elif defined(ARMCM33_DSP_FP_TZ)
#define CMSIS_device_header "ARMCM33_DSP_FP_TZ.h"
#elif defined(ARMCM35P)
#define CMSIS_device_header "ARMCM35P.h"
#elif defined(ARMCM35P_DSP_FP_TZ)
#define CMSIS_device_header "ARMCM35P_DSP_FP_TZ.h"
#elif defined(ARMCM55)
#define CMSIS_device_header "ARMCM55.h"
#elif defined(ARMCA5)
#define CMSIS_device_header "ARMCA5.h"
#elif defined(ARMCA7)
#define CMSIS_device_header "ARMCA7.h"
#elif defined(ARMCA9)
#define CMSIS_device_header "ARMCA9.h"
#else
#error "Unknown device selection!"
#endif

#ifdef __UVISION_VERSION
#define RTE_Compiler_IO_STDOUT          /* Compiler I/O: STDOUT */
#if defined(ARMCM0) || defined(ARMCM0plus)
#define RTE_Compiler_IO_STDOUT_EVR      /* Compiler I/O: STDOUT EVR */
#ifndef RTE_Compiler_EventRecorder
#define RTE_Compiler_EventRecorder
#endif
#else
#define RTE_Compiler_IO_STDOUT_ITM      /* Compiler I/O: STDOUT ITM */
#endif
#else
#define RTE_Compiler_IO_SEMIHOST
#endif

#endif


text: disputes = balanced.Dispute.query


text:
package models

// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command

import (
	"strconv"

	strfmt "github.com/go-openapi/strfmt"

	"github.com/go-openapi/errors"
	"github.com/go-openapi/swag"
)

// GettableSilences gettable silences
// swagger:model gettableSilences
type GettableSilences []*GettableSilence

// Validate validates this gettable silences
func (m GettableSilences) Validate(formats strfmt.Registry) error {
	var res []error

	for i := 0; i < len(m); i++ {
		if swag.IsZero(m[i]) { // not required
			continue
		}

		if m[i] != nil {
			if err := m[i].Validate(formats); err != nil {
				if ve, ok := err.(*errors.Validation); ok {
					return ve.ValidateName(strconv.Itoa(i))
				}
				return err
			}
		}

	}

	if len(res) > 0 {
		return errors.CompositeValidationError(res...)
	}
	return nil
}


text:
<?php

namespace backend\tests\unit;

class TestCase extends \yii\codeception\TestCase
{
    public $appConfig = '@tests/codeception/config/backend/unit.php';
}


text:
<?php
namespace Media42\Mutator\Strategy\Service;

use Interop\Container\ContainerInterface;
use Interop\Container\Exception\ContainerException;
use Media42\Mutator\Strategy\MediaStrategy;
use Zend\ServiceManager\Exception\ServiceNotCreatedException;
use Zend\ServiceManager\Exception\ServiceNotFoundException;
use Zend\ServiceManager\Factory\FactoryInterface;

class MediaStrategyFactory implements FactoryInterface
{

    /**
     * Create an object
     *
     * @param  ContainerInterface $container
     * @param  string $requestedName
     * @param  null|array $options
     * @return object
     * @throws ServiceNotFoundException if unable to resolve the service.
     * @throws ServiceNotCreatedException if an exception is raised when
     *     creating a service.
     * @throws ContainerException if any other error occurs
     */
    public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
    {
        return new MediaStrategy($container);
    }
}


text:
package com.github.dockerjava.core;

import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.DockerCmdExecFactory;
import com.github.dockerjava.core.DefaultDockerClientConfig.Builder;
import com.github.dockerjava.jaxrs.JerseyDockerCmdExecFactory;

public class DockerClientBuilder {

    private DockerClientImpl dockerClient = null;

    private DockerCmdExecFactory dockerCmdExecFactory = null;

    private DockerClientBuilder(DockerClientImpl dockerClient) {
        this.dockerClient = dockerClient;
    }

    public static DockerClientBuilder getInstance() {
        return new DockerClientBuilder(DockerClientImpl.getInstance());
    }

    public static DockerClientBuilder getInstance(Builder dockerClientConfigBuilder) {
        return getInstance(dockerClientConfigBuilder.build());
    }

    public static DockerClientBuilder getInstance(DockerClientConfig dockerClientConfig) {
        return new DockerClientBuilder(DockerClientImpl.getInstance(dockerClientConfig));
    }

    public static DockerClientBuilder getInstance(String serverUrl) {
        return new DockerClientBuilder(DockerClientImpl.getInstance(serverUrl));
    }

    public static DockerCmdExecFactory getDefaultDockerCmdExecFactory() {
        return new JerseyDockerCmdExecFactory();
    }

    public DockerClientBuilder withDockerCmdExecFactory(DockerCmdExecFactory dockerCmdExecFactory) {
        this.dockerCmdExecFactory = dockerCmdExecFactory;
        return this;
    }

    public DockerClient build() {
        if (dockerCmdExecFactory != null) {
            dockerClient.withDockerCmdExecFactory(dockerCmdExecFactory);
        } else {
            dockerClient.withDockerCmdExecFactory(getDefaultDockerCmdExecFactory());
        }

        return dockerClient;
    }
}


text:
<#
Copyright 2014 ASOS.com Limited

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
#>

function user_list {

	<#

	.SYNOPSIS
		List all of the users that are registered with the server

	.DESCRIPTION
		Although the Chef Web UI provides a method to show the registered users, it can be useful
		to be able to get this on the command line, especially of about to remove some.

		No additional parameters are required for this plugin

	.EXAMPLE

		Invoke-POSHKnife user list

		Will list out the users

	#>

	Write-Log -Message " "
	Write-Log -EVentId PC_INFO_0031 -extra ("Listing", "Users")

	# Get a list of the roles currently on the server
	# This so it can be determined if the role already exists or needs to be created
	$items_on_server = Invoke-ChefQuery -Path "/users"

	if ($script:session.knife.return_results) {
		$items_on_server
	} else {
		# iterate around the items that have been returned based on the type that has been
		# returned
		if ($items_on_server -is [Object[]]) {

			foreach ($item in $items_on_server) {
				Write-Log -EventId PC_MISC_0000 -extra ($item.user.username)
			}

		} else {
			# Iterate around the items of the server and show list them
			foreach ($item in ($items_on_server.keys | sort)) {

				Write-Log -EventId PC_MISC_0000 -extra ($item)
			}
		}
	}
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>IWritableMount (ComputerCraft 1.63)</title>
<meta name="date" content="2014-04-18">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

dan200.computercraft.api.filesystem

Interface IWritableMount

All Superinterfaces:

IMount

public interface IWritableMount
extends IMount

Represents a part of a virtual filesystem that can be mounted onto a computercraft using IComputerAccess.mount() or IComputerAccess.mountWritable(), that can also be written to.
 Ready made implementations of this interface can be created using ComputerCraftAPI.createSaveDirMount(), or you're free to implement it yourselves!

See Also:

dan200.computercraft.api.ComputerCraftAPI#createSaveDirMount(World, String),
dan200.computercraft.api.peripheral.IComputerAccess#mountWritable(String, dan200.computercraft.api.filesystem.IMount),
IMount

Method Summary

Methods

Modifier and Type
Method and Description

void
delete(java.lang.String path)

Deletes a directory at a given path inside the virtual file system.

long
getRemainingSpace()

Get the ammount of free space on the mount, in bytes.

void
makeDirectory(java.lang.String path)

Creates a directory at a given path inside the virtual file system.

java.io.OutputStream
openForAppend(java.lang.String path)

Opens a file with a given path, and returns an outputstream for appending to it.

java.io.OutputStream
openForWrite(java.lang.String path)

Opens a file with a given path, and returns an outputstream for writing to it.

Methods inherited from interface dan200.computercraft.api.filesystem.IMount

exists, getSize, isDirectory, list, openForRead

Method Detail

makeDirectory

void makeDirectory(java.lang.String path)
                   throws java.io.IOException

Creates a directory at a given path inside the virtual file system.

Parameters:

path - A file path in normalised format, relative to the mount location. ie: "programs/mynewprograms"

Throws:

java.io.IOException

delete

void delete(java.lang.String path)
            throws java.io.IOException

Deletes a directory at a given path inside the virtual file system.

Parameters:

path - A file path in normalised format, relative to the mount location. ie: "programs/myoldprograms"

Throws:

java.io.IOException

openForWrite

java.io.OutputStream openForWrite(java.lang.String path)
                                  throws java.io.IOException

Opens a file with a given path, and returns an outputstream for writing to it.

Parameters:

path - A file path in normalised format, relative to the mount location. ie: "programs/myprogram"

Returns:

a stream for writing to

Throws:

java.io.IOException

openForAppend

java.io.OutputStream openForAppend(java.lang.String path)
                                   throws java.io.IOException

Opens a file with a given path, and returns an outputstream for appending to it.

Parameters:

path - A file path in normalised format, relative to the mount location. ie: "programs/myprogram"

Returns:

a stream for writing to

Throws:

java.io.IOException

getRemainingSpace

long getRemainingSpace()
                       throws java.io.IOException

Get the ammount of free space on the mount, in bytes. You should decrease this value as the user writes to the mount, and write operations should fail once it reaches zero.

Returns:

The ammount of free space, in bytes.

Throws:

java.io.IOException

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
Yet Another TODO App

        <input class="form-control" type="checkbox" ng-model="todo.completed" ng-change="mainCtrl.todoChanged(todo)" title="completed"/>

        <input class="form-control" type="text" ng-model="todo.title" ng-change="mainCtrl.todoChanged(todo)" title="title"/>

        <button class="btn btn-danger" type="button" ng-click="mainCtrl.deleteClicked(todo)">

        </button>

  <button class="btn btn-primary" type="button" ng-click="mainCtrl.createClicked()">New</button>

      <input type="checkbox" ng-model="mainCtrl.hideCompleted" ng-change="mainCtrl.refreshList()"/>
      Hide Completed


text:
  Dancy est
       un village
       localisé dans le département de l'Eure-et-Loir en Centre. Elle comptait 190 habitants en 2008.

Si vous envisagez de venir habiter à Dancy, vous pourrez aisément trouver une maison à acheter.

Le parc d'habitations, à Dancy, se décomposait en 2011 en zero appartements et 115 maisons soit
 un marché plutôt équilibré.

À coté de Dancy sont positionnées géographiquement les villes de
Saint-Maur-sur-le-Loir localisée à 3 km, 381 habitants,
Villiers-Saint-Orien à 2 km, 174 habitants,
Moléans localisée à 6 km, 507 habitants,
Bullainville située à 4 km, 103 habitants,
Nottonville située à 5 km, 274 habitants,
Pré-Saint-Martin située à 6 km, 159 habitants,
 entre autres. De plus, Dancy est située à seulement treize km de Châteaudun.


text:
class Blank(object):
	"""Blank line handler.  This eats leading blank lines."""

	priority = -90

	def match(self, context, line):
		return not line.stripped

	def __call__(self, context):
		try:
			yield context.input.next()
		except StopIteration:
			return


text:
#ifndef SCHED_EXPORT_HH
# define SCHED_EXPORT_HH

# include <libport/compiler.hh>

# ifdef BUILDING_LIBSCHED
#   define SCHED_API ATTRIBUTE_DLLEXPORT
# else
#   define SCHED_API ATTRIBUTE_DLLIMPORT
# endif

#endif // SCHED_EXPORT_HH


text:
{% extends "admin/base_site.html" %}
{% load i18n admin_static %}
{% load sqrl %}

{% block title %}Manage SQRL{% endblock %}
{% block content_title %}
Manage SQRL
{% endblock %}

{% block extrahead %}{{ block.super }}

{% endblock %}

{% block extrastyle %}{{ block.super }}
    <link rel="stylesheet" type="text/css" href="{% static "admin/css/forms.css" %}"/>
{% endblock %}

{% block userlinks %}
    {% url 'django-admindocs-docroot' as docsroot %}
    {% if docsroot %}
        {% trans 'Documentation' %} /
    {% endif %}
    {% trans 'Manage SQRL' %} /
    {% trans 'Log out' %}
{% endblock %}

{% block breadcrumbs %}

        {% trans 'Home' %}
        › {% trans 'Manage SQRL' %}

{% endblock %}

{% block content %}

        {% if not user.sqrl_identity %}

                You dont have SQRL identity associated with your account yet.
                Please use SQRL link/QR code below to associate SQRL identity with your account.

        {% else %}

                Congratulations! You already have SQRL identity associated with your account.
                If you would like to either change or delete existing SQRL identity
                associated with your account, you can do that by selecting appropriate
                option in your SQRL client and then using the SQRL link/QR code below.

                Note: For both changing or deleting your SQRL identity,
                you will need to load your SQRL rescue code.

                Caution: Normally it is not advised to change or delete
                your SQRL identity. Usually these operations are only required when
                SQRL identity is compromised.

        {% endif %}

        {% sqrl as sqrl %}

        <fieldset class="module aligned">

                {% sqrl_status_url_script_tag sqrl %}

                {# redirect to manage page after successful SQRL transaction #}
                <input type="hidden" name="next" value="{% url 'admin-sqrl_manage' %}">

        </fieldset>

        <form  method="get" action="{{ sqrl.sqrl_url }}" class="sqrl">

                <input type="hidden" name="nut" value="{{ sqrl.nut.nonce }}">
                <input type="submit" value="Manage SQRL" class="default" style="float: left;">

        </form>

{% endblock %}


text:
package org.project.openbaton.nubomedia.api.openbaton;

import org.openbaton.catalogue.mano.record.NetworkServiceRecord;
import org.openbaton.catalogue.nfvo.Action;

import java.io.Serializable;

/**
 * Created by maa on 21.10.15.
 */
public class OpenbatonEvent implements Serializable{

    private Action action;
    private NetworkServiceRecord payload;

    public OpenbatonEvent() {
    }

    public Action getAction() {
        return action;
    }

    public void setAction(Action action) {
        this.action = action;
    }

    public NetworkServiceRecord getPayload() {
        return payload;
    }

    public void setPayload(NetworkServiceRecord payload) {
        this.payload = payload;
    }
}


text:
package org.sagebionetworks.statistics.workers;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.sagebionetworks.common.util.progress.ProgressCallback;
import org.sagebionetworks.common.util.progress.ProgressingRunner;

/**
 * This is used in place to the real worker during integration tests so that we do not waste resources
 *
 * @author Marco
 *
 */
public class StatisticsMonthlyStatusWatcherWorkerStub implements ProgressingRunner {

	private static final Logger LOG = LogManager.getLogger(StatisticsMonthlyStatusWatcherWorkerStub.class);

	@Override
	public void run(ProgressCallback progressCallback) throws Exception {
		LOG.warn("This is a stub, does nothing");
	}

}


text:
FROM golang:1.15-alpine AS build_base

RUN apk add --no-cache git

# Set the Current Working Directory inside the container
WORKDIR /tmp/cw

# We want to populate the module cache based on the go.{mod,sum} files.
COPY go.mod .
COPY go.sum .

RUN go mod download

COPY . .

# Unit tests
RUN CGO_ENABLED=0 go test -v

# Build the Go app
RUN go build -o ./out/cw .

# Start fresh from a smaller image
FROM alpine:3
RUN apk add ca-certificates

COPY --from=build_base /tmp/cw/out/cw /app/cw

ENTRYPOINT ["/app/cw"]


text:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Transport_warehouse extends CI_Controller
{
    function __construct(){
		parent::__construct();
		$this->load->helper('url','language');
		$this->load->library(array('template','ion_auth','form_validation'));
		$group = array('admin', 'transport warehouse');
		if(!$this->ion_auth->in_group($group)){
			$this->session->set_flashdata('message', 'You must be a Transport Warehouse Manager to view this page');
			redirect('dashboard');
	  	}
	}
    public function index()
    {
        $this->load->helper('xcrud');
        $xcrud = xcrud_get_instance();
        $xcrud->table('tbl_project');
        $xcrud->table_name('Transport Warehouse Tangerang');
        $xcrud->columns('periode,target_revenue,target_cost,revenue,ujo_cost,maintenance_cost,admin_cost,man_power_cost,outsource_cost,beban_aset_cost,beban_leasing_cost,other_cost,bulk,40kg,50kg,claim_semen,penjualan_semen');
        $xcrud->fields('periode,target_revenue,target_cost,revenue,ujo_cost,maintenance_cost,admin_cost,man_power_cost,outsource_cost,beban_aset_cost,beban_leasing_cost,other_cost,bulk,40kg,50kg,claim_semen,penjualan_semen');
        $xcrud->change_type('target_revenue,target_cost,revenue,ujo_cost,maintenance_cost,admin_cost,man_power_cost,outsource_cost,beban_aset_cost,beban_leasing_cost,other_cost,claim_semen,penjualan_semen','price','',array('decimals'=>'0','prefix'=>'Rp'));
        $xcrud->label('claim_semen','Claim Semen (Rp)');
		$xcrud->label('penjualan_semen','Penjualan Semen (Rp)');
		$xcrud->label('40kg','40kg (Sak)');
		$xcrud->label('50kg','50kg (Sak)');
        $xcrud->pass_var('project_name','TRANSPORT WAREHOUSE', 'create');
        $xcrud->pass_var('create_date', date('Y-m-d'), 'create');
        $xcrud->pass_var('update_date', date('Y-m-d'), 'edit');
        $xcrud->pass_var('year', date('Y'), 'create');
        $xcrud->where('project_name =', 'TRANSPORT WAREHOUSE');
        $data['content'] = $xcrud->render();
        $this->template->display('transport/warehouse',$data);
    }
}


text:
# ComplexPrimitiveTypes
Complex list and map types for PHP

# API

The TypedMap and TypedList API support almost the same interface as an Array (see (ArrayObject)[http://php.net/manual/en/class.arrayobject.php] for an example of this)
    the differences are in the key values these two types allow and the icompatability with the array_* functions

# Usage
Simple subclass `TypedList` or `TypedMap` for each kind of list or map you want, then write the `isType()` or `keyType()` and `valueType()` methods.

Example:

```php
class StringList extends TypedList
    {

      /**
       * @param mixed $val
       * @return bool
       */
      protected function isType($val)
      {
          return is_string($val);
      }
  }
```

You can now use StringList as you would a normal array. If someone attempts to put a non string in your list, an exception will be thrown immediately.


text:
The `FormPassword` view helper can be used to render an `<input
type="password">` HTML form input. It is meant to work with the
[Password element](../element/password.md).

## Basic usage

```php
use Zend\Form\Element;

$element = new Element\Password('my-password');

// Within your view...
echo $this->formPassword($element);
```

Output:

```html
<input type="password" name="my-password" value="">
```


text:
package de.tor.tribes.ui.windows;

import de.tor.tribes.io.DataHolder;
import de.tor.tribes.io.TroopAmountFixed;
import de.tor.tribes.types.AllyStatResult;
import de.tor.tribes.types.Attack;
import de.tor.tribes.types.FightReport;
import de.tor.tribes.types.Marker;
import de.tor.tribes.types.Note;
import de.tor.tribes.types.OverallStatResult;
import de.tor.tribes.types.SOSRequest;
import de.tor.tribes.types.SingleAttackerStat;
import de.tor.tribes.types.Tag;
import de.tor.tribes.types.TribeStatResult;
import de.tor.tribes.types.TribeStatsElement;
import de.tor.tribes.types.TribeStatsElement.Stats;
import de.tor.tribes.types.drawing.AbstractForm;
import de.tor.tribes.types.drawing.Rectangle;
import de.tor.tribes.types.ext.Barbarians;
import de.tor.tribes.types.ext.NoAlly;
import de.tor.tribes.types.ext.Village;
import de.tor.tribes.ui.ImageManager;
import de.tor.tribes.util.BBCodeFormatter;
import de.tor.tribes.util.BBSupport;
import de.tor.tribes.util.BuildingSettings;
import de.tor.tribes.util.Constants;
import de.tor.tribes.util.GlobalOptions;
import de.tor.tribes.util.bb.AllyReportStatsFormatter;
import de.tor.tribes.util.bb.AttackListFormatter;
import de.tor.tribes.util.bb.BasicFormatter;
import de.tor.tribes.util.bb.DefStatsFormatter;
import de.tor.tribes.util.bb.FormListFormatter;
import de.tor.tribes.util.bb.KillStatsFormatter;
import de.tor.tribes.util.bb.KnownVillageListFormatter;
import de.tor.tribes.util.bb.MarkerListFormatter;
import de.tor.tribes.util.bb.NoteListFormatter;
import de.tor.tribes.util.bb.OverallReportStatsFormatter;
import de.tor.tribes.util.bb.PointStatsFormatter;
import de.tor.tribes.util.bb.ReportListFormatter;
import de.tor.tribes.util.bb.SosListFormatter;
import de.tor.tribes.util.bb.TagListFormatter;
import de.tor.tribes.util.bb.TribeReportStatsFormatter;
import de.tor.tribes.util.bb.TroopListFormatter;
import de.tor.tribes.util.bb.VillageListFormatter;
import de.tor.tribes.util.bb.WinnerLoserStatsFormatter;
import de.tor.tribes.util.translation.TranslationManager;
import de.tor.tribes.util.translation.Translator;
import de.tor.tribes.util.troops.VillageTroopsHolder;
import de.tor.tribes.util.village.KnownVillage;
import java.awt.Color;
import java.awt.event.ItemEvent;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.DefaultListModel;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 *
 * @author Torridity
 */
public class BBCodeEditor extends javax.swing.JFrame {
    private static Logger logger = LogManager.getLogger("BBCodeEditor");

    private Translator trans = TranslationManager.getTranslator("ui.windows.BBCodeEditor");

    private BasicFormatter element = null;
    private final List<BasicFormatter> elementList = new ArrayList<>();
    private final Map<Class, List<? extends BBSupport>> samples = new HashMap<>();
    private static BBCodeEditor SINGLETON = null;

    public static synchronized BBCodeEditor getSingleton() {
        if (SINGLETON == null) {
            SINGLETON = new BBCodeEditor();
        }
        return SINGLETON;
    }

    /**
     * Creates new form BBCodeEditor
     */
    public BBCodeEditor() {
        super();

        initComponents();
        buildSampleData();

        javax.swing.DefaultComboBoxModel jEditSelectModel = new javax.swing.DefaultComboBoxModel();
        elementList.add(new AttackListFormatter(false)); jEditSelectModel.addElement(trans.get("Angriffe"));
        elementList.add(new AttackListFormatter(true)); jEditSelectModel.addElement(trans.get("Angriffe_IGM"));
        elementList.add(new NoteListFormatter()); jEditSelectModel.addElement(trans.get("Notizen"));
        elementList.add(new VillageListFormatter()); jEditSelectModel.addElement(trans.get("Dorflisten"));
        elementList.add(new SosListFormatter()); jEditSelectModel.addElement(trans.get("SOSAnfragen"));
        elementList.add(new ReportListFormatter()); jEditSelectModel.addElement(trans.get("Kampfbericht"));
        elementList.add(new TagListFormatter()); jEditSelectModel.addElement(trans.get("Gruppen"));
        elementList.add(new TroopListFormatter()); jEditSelectModel.addElement(trans.get("Truppen"));
        elementList.add(new KnownVillageListFormatter()); jEditSelectModel.addElement(trans.get("Dorfgebaeude"));
        elementList.add(new PointStatsFormatter()); jEditSelectModel.addElement(trans.get("Statistik_Punkte"));
        elementList.add(new KillStatsFormatter()); jEditSelectModel.addElement(trans.get("Statistik_Angriff"));
        elementList.add(new DefStatsFormatter()); jEditSelectModel.addElement(trans.get("Statistik_Verteidigung"));
        elementList.add(new WinnerLoserStatsFormatter()); jEditSelectModel.addElement(trans.get("Statistik_Gewinner_Verlierer"));
        elementList.add(new FormListFormatter()); jEditSelectModel.addElement(trans.get("Zeichnungen"));
        elementList.add(new OverallReportStatsFormatter()); jEditSelectModel.addElement(trans.get("Berichtauswertung_Zusammenfassung"));
        elementList.add(new AllyReportStatsFormatter()); jEditSelectModel.addElement(trans.get("Berichtauswertung_Staemme"));
        elementList.add(new TribeReportStatsFormatter()); jEditSelectModel.addElement(trans.get("Berichtauswertung_Spieler"));
        elementList.add(new MarkerListFormatter()); jEditSelectModel.addElement(trans.get("Markierungen"));

        jComboBoxEditSelect.setModel(jEditSelectModel);
        jTextPane1.setBackground(Constants.DS_BACK_LIGHT);

        element = elementList.get(0);

        bBPanel2.setBBChangeListener(this::updatePreview);

        fireExportTypeChangedEvent(new ItemEvent(jApplyButton, 0, null, ItemEvent.SELECTED));

        if (!Constants.DEBUG) {
            GlobalOptions.getHelpBroker().enableHelpKey(getRootPane(), "pages.bb_export", GlobalOptions.getHelpBroker().getHelpSet());
        }
    }

    public void reset() {
        buildSampleData();
        updatePreview();
    }

    private void buildSampleData() {
        samples.clear();
        List<Attack> sampleAttacks = new ArrayList<>(); samples.put(Attack.class, sampleAttacks);
        List<Village> sampleVillages = new ArrayList<>(); samples.put(Village.class, sampleVillages);
        List<FightReport> sampleReports = new ArrayList<>(); samples.put(FightReport.class, sampleReports);
        List<SOSRequest> sampleRequests = new ArrayList<>(); samples.put(SOSRequest.class, sampleRequests);
        List<Tag> sampleTags = new ArrayList<>(); samples.put(Tag.class, sampleTags);
        List<Note> sampleNotes = new ArrayList<>(); samples.put(Note.class, sampleNotes);
        List<Stats> sampleStats = new ArrayList<>(); samples.put(Stats.class, sampleStats);
        List<VillageTroopsHolder> sampleTroops = new ArrayList<>(); samples.put(VillageTroopsHolder.class, sampleTroops);
        List<AbstractForm> sampleForms = new ArrayList<>(); samples.put(AbstractForm.class, sampleForms);
        List<OverallStatResult> sampleOverallResult = new ArrayList<>(); samples.put(OverallStatResult.class, sampleOverallResult);
        List<AllyStatResult> sampleAllyResult = new ArrayList<>(); samples.put(AllyStatResult.class, sampleAllyResult);
        List<TribeStatResult> sampleTribeResult = new ArrayList<>(); samples.put(TribeStatResult.class, sampleTribeResult);
        List<Marker> sampleMarker = new ArrayList<>(); samples.put(Marker.class, sampleMarker);
        List<KnownVillage> sampleKnownVillage = new ArrayList<>(); samples.put(KnownVillage.class, sampleKnownVillage);

        //sample village
        Village sampleVillage1 = DataHolder.getSingleton().getRandomVillageWithOwner();
        //sample attack
        Village sampleVillage2 = DataHolder.getSingleton().getRandomVillageWithOwner();
        Village sampleVillage3 = DataHolder.getSingleton().getRandomVillageWithOwner();
        Village sampleVillage4 = DataHolder.getSingleton().getRandomVillageWithOwner();
        Village sampleVillage5 = DataHolder.getSingleton().getRandomVillageWithOwner();
        if (sampleVillage1 == null) {
            sampleVillage1 = new Village((int) (Math.random() * 1000), (int) (Math.random() * 1000));
        }
        if (sampleVillage2 == null) {
            sampleVillage2 = new Village((int) (Math.random() * 1000), (int) (Math.random() * 1000));
        }
        if (sampleVillage3 == null) {
            sampleVillage3 = new Village((int) (Math.random() * 1000), (int) (Math.random() * 1000));
        }
        if (sampleVillage4 == null) {
            sampleVillage4 = new Village((int) (Math.random() * 1000), (int) (Math.random() * 1000));
        }
        if (sampleVillage5 == null) {
            sampleVillage5 = new Village((int) (Math.random() * 1000), (int) (Math.random() * 1000));
        }
        sampleVillages.add(sampleVillage2);
        sampleVillages.add(sampleVillage3);
        sampleVillages.add(sampleVillage4);
        sampleVillages.add(sampleVillage5);
        Attack sampleAttack = new Attack();
        sampleAttack.setSource(sampleVillage2);
        sampleAttack.setTarget(sampleVillage3);
        sampleAttack.setArriveTime(new Date());
        sampleAttack.setType(Attack.CLEAN_TYPE);
        sampleAttack.setUnit(DataHolder.getSingleton().getRandomUnit());
        sampleAttack.setTroopsByType();
        Attack sampleAttack2 = new Attack();
        sampleAttack2.setSource(sampleVillage2);
        sampleAttack2.setTarget(sampleVillage3);
        sampleAttack2.setArriveTime(new Date());
        sampleAttack2.setType(Attack.CLEAN_TYPE);
        sampleAttack2.setUnit(DataHolder.getSingleton().getRandomUnit());
        sampleAttack2.setTroopsByType();
        sampleAttacks.add(sampleAttack);
        sampleAttacks.add(sampleAttack2);
        //sample note
        Note sampleNote = new Note();
        sampleNote.setNoteSymbol(ImageManager.NOTE_SYMBOL_BALL_BLUE);
        sampleNote.setTimestamp(System.currentTimeMillis());
        sampleNote.addVillage(sampleVillage1);
        sampleNote.addVillage(sampleVillage4);
        sampleNote.addVillage(sampleVillage5);
        sampleNote.setNoteText(trans.get("Beispielnotiz"));
        Note sampleNote2 = new Note();
        sampleNote2.setNoteSymbol(ImageManager.NOTE_SYMBOL_BALL_RED);
        sampleNote2.setTimestamp(System.currentTimeMillis());
        sampleNote2.addVillage(sampleVillage4);
        sampleNote2.addVillage(sampleVillage5);
        sampleNote2.setNoteText(trans.get("weitereBeispielnotiz"));
        sampleNotes.add(sampleNote);
        sampleNotes.add(sampleNote2);
        //sample SOS request
        SOSRequest sampleSOSRequest = new SOSRequest();
        sampleSOSRequest.setDefender(Barbarians.getSingleton());
        sampleSOSRequest.addTarget(sampleVillage4);
        sampleSOSRequest.getTargetInformation(sampleVillage4).setWallLevel(20);
        sampleSOSRequest.getTargetInformation(sampleVillage4).addAttack(sampleVillage2, new Date());
        sampleSOSRequest.getTargetInformation(sampleVillage4).addAttack(sampleVillage2, new Date());
        sampleSOSRequest.getTargetInformation(sampleVillage4).addTroopInformation(DataHolder.getSingleton().getRandomUnit(), 300);
        sampleSOSRequest.addTarget(sampleVillage5);
        sampleSOSRequest.getTargetInformation(sampleVillage5).setWallLevel(10);
        sampleSOSRequest.getTargetInformation(sampleVillage5).addAttack(sampleVillage2, new Date());
        sampleSOSRequest.getTargetInformation(sampleVillage5).addAttack(sampleVillage2, new Date());
        sampleSOSRequest.getTargetInformation(sampleVillage5).addTroopInformation(DataHolder.getSingleton().getRandomUnit(), 100);
        sampleRequests.add(sampleSOSRequest);
        //sampleRequests.add(sampleSOSRequest2);
        //sample report
        FightReport sampleReport = new FightReport();
        sampleReport.setAimedBuildingId(BuildingSettings.getBuildingIdByName("wall"));
        sampleReport.setAttacker(sampleVillage2.getTribe());
        sampleReport.setDefender(sampleVillage3.getTribe());
        sampleReport.setLuck(0d);
        sampleReport.setMoral(100d);
        sampleReport.setSourceVillage(sampleVillage2);
        sampleReport.setTargetVillage(sampleVillage3);
        sampleReport.setWallAfter((byte) 15);
        sampleReport.setWallBefore((byte) 20);
        FightReport sampleReport2 = new FightReport();
        sampleReport2.setAcceptanceAfter((byte) 70);
        sampleReport2.setAcceptanceBefore((byte) 100);
        sampleReport2.setAimedBuildingId(BuildingSettings.getBuildingIdByName("wall"));
        sampleReport2.setAttacker(sampleVillage2.getTribe());
        sampleReport2.setDefender(sampleVillage3.getTribe());
        sampleReport2.setLuck(0d);
        sampleReport2.setMoral(100d);
        sampleReport2.setSourceVillage(sampleVillage2);
        sampleReport2.setTargetVillage(sampleVillage3);
        sampleReport2.setWallAfter((byte) 15);
        sampleReport2.setWallBefore((byte) 20);
        sampleReports.add(sampleReport);
        sampleReports.add(sampleReport2);
        Tag t = new Tag(trans.get("MeineGruppe"), false);
        t.setTagIcon(0);
        t.setTagColor(Color.RED);
        Tag t2 = new Tag(trans.get("Gruppe2"), false);
        t2.setTagIcon(1);
        t2.setTagColor(Color.BLUE);
        Tag t3 = new Tag(trans.get("NocheineGruppe"), false);
        t3.setTagIcon(5);
        t3.setTagColor(Color.GREEN);
        sampleTags.add(t);
        sampleTags.add(t2);
        sampleTags.add(t3);
        t.tagVillage(sampleVillage2.getId());
        t.tagVillage(sampleVillage3.getId());
        t2.tagVillage(sampleVillage4.getId());
        t3.tagVillage(sampleVillage5.getId());
        //sample troops
        VillageTroopsHolder h = new VillageTroopsHolder(sampleVillage1, new Date());
        TroopAmountFixed troops = new TroopAmountFixed(0);
        troops.setAmountForUnit(DataHolder.getSingleton().getUnitByPlainName("axe"), 6600);
        troops.setAmountForUnit(DataHolder.getSingleton().getUnitByPlainName("light"), 2200);
        troops.setAmountForUnit(DataHolder.getSingleton().getUnitByPlainName("ram"), 300);
        troops.setAmountForUnit(DataHolder.getSingleton().getUnitByPlainName("snob"), 2);
        h.setTroops(troops);
        VillageTroopsHolder h2 = new VillageTroopsHolder(sampleVillage3, new Date());
        troops.setAmountForUnit(DataHolder.getSingleton().getUnitByPlainName("axe"), 5500);
        troops.setAmountForUnit(DataHolder.getSingleton().getUnitByPlainName("light"), 2000);
        troops.setAmountForUnit(DataHolder.getSingleton().getUnitByPlainName("marcher"), 300);
        troops.setAmountForUnit(DataHolder.getSingleton().getUnitByPlainName("ram"), 240);
        h2.setTroops(troops);
        sampleTroops.add(h);
        sampleTroops.add(h2);

        //sample known village
        KnownVillage knV1 = new KnownVillage(sampleVillage1);
        KnownVillage knV2 = new KnownVillage(sampleVillage2);
        KnownVillage knV3 = new KnownVillage(sampleVillage3);
        KnownVillage knV4 = new KnownVillage(sampleVillage4);
        for (String buildingName : BuildingSettings.BUILDING_NAMES) {
            int max = BuildingSettings.getMaxBuildingLevel(buildingName);
            int min = BuildingSettings.getMinBuildingLevel(buildingName);
            if(max < 1) continue;
            knV1.setBuildingLevelByName(buildingName, (int) (Math.random()*(max-min) + min));
            knV2.setBuildingLevelByName(buildingName, (int) (Math.random()*(max-min) + min));
            knV3.setBuildingLevelByName(buildingName, (int) (Math.random()*(max-min) + min));
            knV4.setBuildingLevelByName(buildingName, (int) (Math.random()*(max-min) + min));
        }
        sampleKnownVillage.add(knV1);
        sampleKnownVillage.add(knV2);
        sampleKnownVillage.add(knV3);
        sampleKnownVillage.add(knV4);

        //build stats
        TribeStatsElement e1 = new TribeStatsElement(sampleVillage2.getTribe());
        e1.addRandomSnapshots();
        TribeStatsElement e2 = new TribeStatsElement(sampleVillage3.getTribe());
        e2.addRandomSnapshots();
        sampleStats.add(e1.generateStats(e1.getTimestamps()[0], e1.getTimestamps()[1]));
        sampleStats.add(e2.generateStats(e2.getTimestamps()[0], e2.getTimestamps()[1]));
        //build form
        Rectangle r = new Rectangle();
        r.setFormName(trans.get("Beispielzeichnung"));
        r.setDrawColor(Color.BLUE);
        r.setXPos(500);
        r.setYPos(500);
        r.setXPosEnd(505);
        r.setYPosEnd(505);
        sampleForms.add(r);
        //build report stats
        SingleAttackerStat tribeStat1 = SingleAttackerStat.createRandomElement(sampleVillage1.getTribe());
        SingleAttackerStat tribeStat2 = SingleAttackerStat.createRandomElement(sampleVillage2.getTribe());
        TribeStatResult tribeResult1 = new TribeStatResult();
        tribeResult1.setTribeStats(tribeStat1, true);
        TribeStatResult tribeResult2 = new TribeStatResult();
        tribeResult2.setTribeStats(tribeStat2, true);

        AllyStatResult allyStat1 = new AllyStatResult();
        allyStat1.setAlly((sampleVillage1.getTribe() != null && sampleVillage1.getTribe().getAlly() != null) ? sampleVillage1.getTribe().getAlly() : NoAlly.getSingleton());
        allyStat1.addTribeStatResult(tribeResult1);

        AllyStatResult allyStat2 = new AllyStatResult();
        allyStat2.setAlly((sampleVillage2.getTribe() != null && sampleVillage2.getTribe().getAlly() != null) ? sampleVillage2.getTribe().getAlly() : NoAlly.getSingleton());
        allyStat2.addTribeStatResult(tribeResult2);

        OverallStatResult overallResult = new OverallStatResult();
        overallResult.addAllyStatsResult(allyStat1);
        overallResult.addAllyStatsResult(allyStat2);
        overallResult.setDefenders(10);
        overallResult.setAttackerAllies(2);
        overallResult.setDefenderAllies(1);
        overallResult.setReportCount(100);
        overallResult.setStartDate(new Date());
        overallResult.setEndDate(new Date());

        allyStat1.setOverallKills(overallResult.getKills());
        allyStat1.setOverallLosses(overallResult.getLosses());
        allyStat2.setOverallKills(overallResult.getKills());
        allyStat2.setOverallLosses(overallResult.getLosses());
        tribeResult1.setAllyKills(allyStat1.getKills());
        tribeResult1.setAllyLosses(allyStat1.getLosses());
        tribeResult1.setOverallKills(allyStat1.getOverallKills());
        tribeResult1.setOverallLosses(allyStat1.getOverallLosses());

        tribeResult2.setAllyKills(allyStat2.getKills());
        tribeResult2.setAllyLosses(allyStat2.getLosses());
        tribeResult2.setOverallKills(allyStat2.getOverallKills());
        tribeResult2.setOverallLosses(allyStat2.getOverallLosses());

        sampleTribeResult.add(tribeResult1);
        sampleTribeResult.add(tribeResult2);
        sampleAllyResult.add(allyStat1);
        sampleAllyResult.add(allyStat2);
        sampleOverallResult.add(overallResult);
        Marker m1 = new Marker();
        m1.setMarkerType(Marker.MarkerType.TRIBE);
        m1.setMarkerID(sampleVillage1.getTribeID());
        m1.setMarkerColor(Constants.ENEMY_MARKER);
        Marker m2 = new Marker();
        m2.setMarkerType(Marker.MarkerType.TRIBE);
        m2.setMarkerID(sampleVillage2.getTribeID());
        m2.setMarkerColor(Constants.NAP_MARKER);
        sampleMarker.add(m1);
        sampleMarker.add(m2);
    }

    /**
     * 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() {
        java.awt.GridBagConstraints gridBagConstraints;

        jScrollPane1 = new javax.swing.JScrollPane();
        jTextPane1 = new javax.swing.JTextPane();
        jApplyButton = new javax.swing.JButton();
        jStandardButton = new javax.swing.JButton();
        jBBPanel = new javax.swing.JPanel();
        bBPanel2 = new de.tor.tribes.ui.panels.BBPanel();
        infoPanel = new org.jdesktop.swingx.JXCollapsiblePane();
        jScrollPane2 = new javax.swing.JScrollPane();
        jVarsList = new javax.swing.JList();
        jPanelEditSelect = new javax.swing.JPanel();
        jComboBoxEditSelect = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        jButton3 = new javax.swing.JButton();

        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                onClose(evt);
            }
        });
        getContentPane().setLayout(new java.awt.GridBagLayout());

        jScrollPane1.setBorder(javax.swing.BorderFactory.createTitledBorder(trans.get("Vorschau")));
        jScrollPane1.setMinimumSize(new java.awt.Dimension(33, 150));
        jScrollPane1.setPreferredSize(new java.awt.Dimension(33, 150));

        jTextPane1.setContentType("text/html"); // NOI18N
        jScrollPane1.setViewportView(jTextPane1);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.gridwidth = 3;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10);
        getContentPane().add(jScrollPane1, gridBagConstraints);

        jApplyButton.setText(trans.get("Schliessen"));
        jApplyButton.setToolTipText(trans.get("BBBeendet"));
        jApplyButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                fireApplyBBTemplatesEvent(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        gridBagConstraints.insets = new java.awt.Insets(10, 5, 10, 10);
        getContentPane().add(jApplyButton, gridBagConstraints);

        jStandardButton.setText(trans.get("Standardwiederherstellen"));
        jStandardButton.setToolTipText(trans.get("Standard_Text"));
        jStandardButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                fireResetEvent(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 5);
        getContentPane().add(jStandardButton, gridBagConstraints);

        jBBPanel.setBackground(new java.awt.Color(239, 235, 223));
        jBBPanel.setLayout(new java.awt.BorderLayout());

        bBPanel2.setMinimumSize(new java.awt.Dimension(363, 150));
        bBPanel2.setPreferredSize(new java.awt.Dimension(363, 251));
        jBBPanel.add(bBPanel2, java.awt.BorderLayout.CENTER);

        infoPanel.setAnimated(false);
        infoPanel.setCollapsed(true);
        infoPanel.setDirection(org.jdesktop.swingx.JXCollapsiblePane.Direction.LEFT);
        infoPanel.setInheritAlpha(false);

        jScrollPane2.setBorder(javax.swing.BorderFactory.createTitledBorder(trans.get("Variablen")));

        jVarsList.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jScrollPane2.setViewportView(jVarsList);

        infoPanel.add(jScrollPane2, java.awt.BorderLayout.PAGE_START);

        jBBPanel.add(infoPanel, java.awt.BorderLayout.EAST);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.gridwidth = 3;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10);
        getContentPane().add(jBBPanel, gridBagConstraints);

        jPanelEditSelect.setLayout(new java.awt.BorderLayout(5, 0));

        jComboBoxEditSelect.setMinimumSize(new java.awt.Dimension(66, 20));
        jComboBoxEditSelect.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                fireExportTypeChangedEvent(evt);
            }
        });
        jPanelEditSelect.add(jComboBoxEditSelect, java.awt.BorderLayout.CENTER);

        jLabel1.setText(trans.get("ExportTemplate"));
        jPanelEditSelect.add(jLabel1, java.awt.BorderLayout.WEST);

        jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/ui/information.png"))); // NOI18N
        jButton3.setToolTipText(trans.get("Platzhalter"));
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                fireShowTemplateVarsDialogEvent(evt);
            }
        });
        jPanelEditSelect.add(jButton3, java.awt.BorderLayout.EAST);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridwidth = 3;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10);
        getContentPane().add(jPanelEditSelect, gridBagConstraints);

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

    private void fireExportTypeChangedEvent(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_fireExportTypeChangedEvent
        String result = "";
        if (evt.getStateChange() == ItemEvent.SELECTED) {
            element = elementList.get(jComboBoxEditSelect.getSelectedIndex());
            bBPanel2.setBBCode(element.getTemplate());
            result = element.formatElements(samples.get(element.getConvertableType()), true);
        }

        DefaultListModel model = new DefaultListModel();
        for (String var : element.getTemplateVariables()) {
            model.addElement(var);
        }

        jTextPane1.setText(BBCodeFormatter.toHtml(result));

        jVarsList.setModel(model);
    }//GEN-LAST:event_fireExportTypeChangedEvent

    private void fireShowTemplateVarsDialogEvent(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fireShowTemplateVarsDialogEvent
        infoPanel.setCollapsed(!infoPanel.isCollapsed());
    }//GEN-LAST:event_fireShowTemplateVarsDialogEvent

    private void fireApplyBBTemplatesEvent(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fireApplyBBTemplatesEvent
        setVisible(false);
    }//GEN-LAST:event_fireApplyBBTemplatesEvent

    private void fireResetEvent(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fireResetEvent
        element = elementList.get(jComboBoxEditSelect.getSelectedIndex());
        bBPanel2.setBBCode(element.getStandardTemplate());
        updatePreview();
    }//GEN-LAST:event_fireResetEvent

    private void onClose(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_onClose
        bBPanel2.hideAllSubelements();
    }//GEN-LAST:event_onClose

    private void updatePreview() {
        String result = "";
        element = elementList.get(jComboBoxEditSelect.getSelectedIndex());
        GlobalOptions.addProperty(element.getPropertyKey(), bBPanel2.getBBCode());
        result = element.formatElements(samples.get(element.getConvertableType()), true);

        try {
            jTextPane1.setText("<html><head>" + BBCodeFormatter.getStyles() + "</head><body>" + BBCodeFormatter.toHtml(result) + "</body></html>");
        } catch (Exception e) {
            logger.error("Exception during update", e);
        }
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private de.tor.tribes.ui.panels.BBPanel bBPanel2;
    private org.jdesktop.swingx.JXCollapsiblePane infoPanel;
    private javax.swing.JButton jApplyButton;
    private javax.swing.JPanel jBBPanel;
    private javax.swing.JButton jButton3;
    private javax.swing.JComboBox jComboBoxEditSelect;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanelEditSelect;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JButton jStandardButton;
    private javax.swing.JTextPane jTextPane1;
    private javax.swing.JList jVarsList;
    // End of variables declaration//GEN-END:variables
}