<#--
  Licensed to the Apache Software Foundation (ASF) under one
  or more contributor license agreements.  See the NOTICE file
  distributed with this work for additional information
  regarding copyright ownership.  The ASF licenses this file
  to you 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.
-->
<#assign licenseFirst = "/*">
<#assign licensePrefix = " * ">
<#assign licenseLast = " */">
<#include "${project.licensePath}">

<#if package?? && package != "">
package ${package};

</#if>
import java.awt.EventQueue;
import java.beans.Beans;
import java.util.ArrayList;/* DETAIL_ONLY */
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;/* DETAIL_ONLY */
import java.util.List;
import javax.persistence.RollbackException;
import javax.swing.JFrame;
import javax.swing.JPanel;

/**
 *
 * @author ${user}
 */
public class ${name} extends JPanel {

    public ${name}() {
        initComponents();
        if (!Beans.isDesignTime()) {
            entityManager.getTransaction().begin();
        }
    }

    /** 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() {
    }// </editor-fold>//GEN-END:initComponents

    /* DETAIL_ONLY */
    private void deleteDetailButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteDetailButtonActionPerformed
        int index = masterTable.getSelectedRow();
        _masterClass_ _masterEntityInitial_ = list.get(/* JDK6ONLY */masterTable.convertRowIndexToModel(/* JDK6ONLY */index/* JDK6ONLY */)/* JDK6ONLY */);
        Collection<_detailClass_> _detailEntityInitial_s = _masterEntityInitial_.get_joinCollectionCapital_();
        int[] selected = detailTable.getSelectedRows();
        List<_detailClass_> toRemove = new ArrayList<_detailClass_>(selected.length);
        for (int idx=0; idx<selected.length; idx++) {/* JDK6ONLY */
            selected[idx] = detailTable.convertRowIndexToModel(selected[idx]);/* JDK6ONLY */
            int count = 0;
            Iterator<_detailClass_> iter = _detailEntityInitial_s.iterator();
            while (count++ < selected[idx]) iter.next();
            _detailClass_ _detailEntityInitial_ = iter.next();
            toRemove.add(_detailEntityInitial_);
            entityManager.remove(_detailEntityInitial_);
        }
        _detailEntityInitial_s.removeAll(toRemove);
        masterTable.clearSelection();
        masterTable.setRowSelectionInterval(index, index);
    }//GEN-LAST:event_deleteDetailButtonActionPerformed

    private void newDetailButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newDetailButtonActionPerformed
        int index = masterTable.getSelectedRow();
        _masterClass_ _masterEntityInitial_ = list.get(/* JDK6ONLY */masterTable.convertRowIndexToModel(/* JDK6ONLY */index/* JDK6ONLY */)/* JDK6ONLY */);
        Collection<_detailClass_> _detailEntityInitial_s = _masterEntityInitial_.get_joinCollectionCapital_();
        if (_detailEntityInitial_s == null) {
            _detailEntityInitial_s = new LinkedList<_detailClass_>();
            _masterEntityInitial_.set_joinCollectionCapital_((List)_detailEntityInitial_s);
        }
        _detailClass_ _detailEntityInitial_ = new _detailClass_();
        entityManager.persist(_detailEntityInitial_);
        _detailEntityInitial_.set_joinCapital_(_masterEntityInitial_);
        _detailEntityInitial_s.add(_detailEntityInitial_);
        masterTable.clearSelection();
        masterTable.setRowSelectionInterval(index, index);
        int row = _detailEntityInitial_s.size()-1;
        detailTable.setRowSelectionInterval(row, row);
        detailTable.scrollRectToVisible(detailTable.getCellRect(row, 0, true));
    }//GEN-LAST:event_newDetailButtonActionPerformed
    /* DETAIL_ONLY */
    @SuppressWarnings("unchecked")
    private void refreshButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_refreshButtonActionPerformed
        entityManager.getTransaction().rollback();
        entityManager.getTransaction().begin();
        java.util.Collection data = query.getResultList();
        for (Object entity : data) {
            entityManager.refresh(entity);
        }
        list.clear();
        list.addAll(data);
    }//GEN-LAST:event_refreshButtonActionPerformed

    private void deleteButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteButtonActionPerformed
        int[] selected = masterTable.getSelectedRows();
        List<_masterClass_> toRemove = new ArrayList<_masterClass_>(selected.length);
        for (int idx=0; idx<selected.length; idx++) {
            _masterClass_ _masterEntityInitial_ = list.get(/* JDK6ONLY */masterTable.convertRowIndexToModel(/* JDK6ONLY */selected[idx]/* JDK6ONLY */)/* JDK6ONLY */);
            toRemove.add(_masterEntityInitial_);
            entityManager.remove(_masterEntityInitial_);
        }
        list.removeAll(toRemove);
    }//GEN-LAST:event_deleteButtonActionPerformed

    private void newButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newButtonActionPerformed
        _masterClass_ _masterEntityInitial_ = new _masterClass_();
        entityManager.persist(_masterEntityInitial_);
        list.add(_masterEntityInitial_);
        int row = list.size()-1;
        masterTable.setRowSelectionInterval(row, row);
        masterTable.scrollRectToVisible(masterTable.getCellRect(row, 0, true));
    }//GEN-LAST:event_newButtonActionPerformed
    
    private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed
        try {
            entityManager.getTransaction().commit();
            entityManager.getTransaction().begin();
        } catch (RollbackException rex) {
            rex.printStackTrace();
            entityManager.getTransaction().begin();
            List<_masterClass_> merged = new ArrayList<_masterClass_>(list.size());
            for (_masterClass_ _masterEntityInitial_ : list) {
                merged.add(entityManager.merge(_masterEntityInitial_));
            }
            list.clear();
            list.addAll(merged);
        }
    }//GEN-LAST:event_saveButtonActionPerformed
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    // End of variables declaration//GEN-END:variables
    
    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(${name}.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(${name}.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(${name}.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(${name}.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                JFrame frame = new JFrame();
                frame.setContentPane(new ${name}());
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.pack();
                frame.setVisible(true);
            }
        });
    }

}
