/*
 * Copyright (C) 2017 chcan
 *
 * 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/>.
 */
package controlador.editores;

import controlador.Editor;
import desenho.preDiagrama.baseDrawerItem;
import diagramas.logico.Campo;
import diagramas.logico.Constraint;
import diagramas.logico.DiagramaLogico;
import diagramas.logico.Tabela;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ItemEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import javax.swing.DefaultListModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

/**
 *
 * @author chcan
 */
public class EditorDeIrUnique extends javax.swing.JDialog {

    /**
     * Creates new form EditorDeCampos
     */
    public EditorDeIrUnique(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        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() {

        jPanel1 = new javax.swing.JPanel();
        comboTabelas = new javax.swing.JComboBox<>();
        jLabel1 = new javax.swing.JLabel();
        jSplitPane1 = new javax.swing.JSplitPane();
        jPanel3 = new javax.swing.JPanel();
        jScrollPane3 = new javax.swing.JScrollPane();
        Listador = new javax.swing.JList<>();
        jToolBar3 = new javax.swing.JToolBar();
        jSeparator7 = new javax.swing.JToolBar.Separator();
        btnUP2 = new javax.swing.JButton();
        btnDown2 = new javax.swing.JButton();
        jSeparator8 = new javax.swing.JToolBar.Separator();
        btnAdd = new javax.swing.JButton();
        btnDel = new javax.swing.JButton();
        jSeparator9 = new javax.swing.JToolBar.Separator();
        jPanel4 = new javax.swing.JPanel();
        jPanel5 = new javax.swing.JPanel();
        chkIsnomeada = new javax.swing.JCheckBox();
        jLabel2 = new javax.swing.JLabel();
        txtNome = new javax.swing.JTextField();
        jToolBar1 = new javax.swing.JToolBar();
        Adicionar = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        Principal = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        mostrador = new javax.swing.JTextArea();
        jPanel2 = new javax.swing.JPanel();
        btnPronto = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("principal/Formularios_pt_BR"); // NOI18N
        setTitle(bundle.getString("EditorDeCampos.title")); // NOI18N

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(Editor.fromConfiguracao.getValor("Inspector.obj.constraint.unique")));

        comboTabelas.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        comboTabelas.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                comboTabelasActionPerformed(evt);
            }
        });

        jLabel1.setText(bundle.getString("EditorDeIR.Tabela.selecionada")); // NOI18N

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(comboTabelas, javax.swing.GroupLayout.PREFERRED_SIZE, 335, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(comboTabelas, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        jSplitPane1.setDividerLocation(220);
        jSplitPane1.setResizeWeight(0.1);

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

        jToolBar3.setFloatable(false);
        jToolBar3.setOrientation(javax.swing.SwingConstants.VERTICAL);
        jToolBar3.setRollover(true);
        jToolBar3.add(jSeparator7);

        btnUP2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/up.png"))); // NOI18N
        btnUP2.setText(bundle.getString("FormHelp.btnUP2.text")); // NOI18N
        btnUP2.setToolTipText(bundle.getString("FormHelp.btnUP2.toolTipText")); // NOI18N
        btnUP2.setFocusable(false);
        btnUP2.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnUP2.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnUP2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnUP2ActionPerformed(evt);
            }
        });
        jToolBar3.add(btnUP2);

        btnDown2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/down.png"))); // NOI18N
        btnDown2.setToolTipText(bundle.getString("FormHelp.btnDown2.toolTipText")); // NOI18N
        btnDown2.setFocusable(false);
        btnDown2.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnDown2.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnDown2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDown2ActionPerformed(evt);
            }
        });
        jToolBar3.add(btnDown2);
        jToolBar3.add(jSeparator8);

        btnAdd.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/add_16.gif"))); // NOI18N
        btnAdd.setText(bundle.getString("FormHelp.btnAdd.text")); // NOI18N
        btnAdd.setToolTipText(bundle.getString("FormHelp.btnAdd.toolTipText")); // NOI18N
        btnAdd.setActionCommand(bundle.getString("FormHelp.btnAdd.actionCommand")); // NOI18N
        btnAdd.setFocusable(false);
        btnAdd.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnAdd.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddActionPerformed(evt);
            }
        });
        jToolBar3.add(btnAdd);

        btnDel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/busy.png"))); // NOI18N
        btnDel.setText(bundle.getString("FormHelp.btnDel.text")); // NOI18N
        btnDel.setToolTipText(bundle.getString("FormHelp.btnDel.toolTipText")); // NOI18N
        btnDel.setFocusable(false);
        btnDel.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnDel.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnDel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDelActionPerformed(evt);
            }
        });
        jToolBar3.add(btnDel);
        jToolBar3.add(jSeparator9);

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                .addGap(30, 30, 30)
                .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 189, Short.MAX_VALUE))
            .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel3Layout.createSequentialGroup()
                    .addComponent(jToolBar3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(0, 194, Short.MAX_VALUE)))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 415, Short.MAX_VALUE)
            .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jToolBar3, javax.swing.GroupLayout.DEFAULT_SIZE, 415, Short.MAX_VALUE))
        );

        jSplitPane1.setLeftComponent(jPanel3);

        chkIsnomeada.setText(bundle.getString("EditorDeIR.nomeada")); // NOI18N

        jLabel2.setText(bundle.getString("EditorDeIR.lblIR.nome")); // NOI18N

        txtNome.setText("jTextField1");

        javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
        jPanel5.setLayout(jPanel5Layout);
        jPanel5Layout.setHorizontalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(chkIsnomeada)
                .addGap(44, 44, 44)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(txtNome, javax.swing.GroupLayout.PREFERRED_SIZE, 154, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel5Layout.setVerticalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(chkIsnomeada)
                    .addComponent(jLabel2)
                    .addComponent(txtNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(0, 0, Short.MAX_VALUE))
        );

        jToolBar1.setFloatable(false);
        jToolBar1.setRollover(true);

        Adicionar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/mais.png"))); // NOI18N
        Adicionar.setText(bundle.getString("EditorDeIR.Adicionar.Campo")); // NOI18N
        Adicionar.setFocusable(false);
        Adicionar.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        Adicionar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        Adicionar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                AdicionarActionPerformed(evt);
            }
        });
        jToolBar1.add(Adicionar);

        Principal.setBackground(new java.awt.Color(204, 204, 204));
        Principal.setLayout(null);
        jScrollPane1.setViewportView(Principal);

        mostrador.setEditable(false);
        mostrador.setColumns(20);
        mostrador.setRows(5);
        jScrollPane2.setViewportView(mostrador);

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jToolBar1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jScrollPane1)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 570, Short.MAX_VALUE)
            .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addGap(0, 0, 0)
                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 280, Short.MAX_VALUE)
                .addGap(1, 1, 1)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, 0))
        );

        jSplitPane1.setRightComponent(jPanel4);

        jPanel2.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        btnPronto.setText(bundle.getString("EditorDeCampos.Fechar")); // NOI18N
        btnPronto.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnProntoActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap(717, Short.MAX_VALUE)
                .addComponent(btnPronto)
                .addGap(2, 2, 2))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addGap(0, 0, 0)
                .addComponent(btnPronto))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jSplitPane1, javax.swing.GroupLayout.Alignment.TRAILING))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 424, Short.MAX_VALUE)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(47, 47, 47)
                    .addComponent(jSplitPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 417, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(30, Short.MAX_VALUE)))
        );

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

    private void btnProntoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnProntoActionPerformed
        DoneTexto();
        this.setVisible(false);
    }//GEN-LAST:event_btnProntoActionPerformed

    int v = 0;

    private void AdicionarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AdicionarActionPerformed
        Campo c = getSelecionada().Add(Editor.fromConfiguracao.getValor("diagrama.Campo.nome"));
        AdicionarPainel(c);
        getSelecionada().DoMuda();
    }//GEN-LAST:event_AdicionarActionPerformed

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

    private void btnUP2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnUP2ActionPerformed
        performMove(-1);
    }//GEN-LAST:event_btnUP2ActionPerformed

    private void btnDown2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDown2ActionPerformed
        performMove(1);
    }//GEN-LAST:event_btnDown2ActionPerformed

    private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddActionPerformed
        Constraint cc = new Constraint(getSelecionada());
        cc.setTipo(Constraint.CONSTRAINT_TIPO.tpUNIQUE);
        getSelecionada().repaint();
        Popule(getSelecionada());
        Listador.setSelectedIndex(Listador.getModel().getSize() - 1);
    }//GEN-LAST:event_btnAddActionPerformed

    private void btnDelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDelActionPerformed
        getSelecionada().RemoveConstraint(selConstr);
        Popule(getSelecionada());
    }//GEN-LAST:event_btnDelActionPerformed

    private void Done() {
        Constraint pk = getSelConstr();
        if (pk == null) {
            chkIsnomeada.setSelected(false);
            txtNome.setText("");
            txtNome.setEnabled(false);
            return;
        }
        chkIsnomeada.setSelected(pk.isNomeada());
        txtNome.setEnabled(pk.isNomeada());
        txtNome.setText(pk.getNome());
        mostrador.setText(pk.getDDL());
    }

    private void DoneTexto() {
        Constraint pk = getSelConstr();
        if (pk == null) {
            chkIsnomeada.setSelected(false);
            txtNome.setText("");
            txtNome.setEnabled(false);
            mostrador.setText("");
            return;
        }
        if (pk.isNomeada() != chkIsnomeada.isSelected() || !pk.getNome().equals(txtNome.getText())) {
            pk.setNomeada(chkIsnomeada.isSelected());
            pk.setNome(txtNome.getText());
            getSelecionada().DoMuda();
            PopuleLista();
        }
        txtNome.setEnabled(pk.isNomeada());
        txtNome.setText(pk.getNome());
        mostrador.setText(pk.getDDL());
    }

    private void performMove(int passo) {
        List<Constraint> lst = getSelecionada().getConstraints().stream().filter(c -> c.getTipo() == Constraint.CONSTRAINT_TIPO.tpUNIQUE).collect(Collectors.toList());
        int ix = lst.indexOf(selConstr) + passo;
        Constraint dest = lst.get(ix);
        int idx = getSelecionada().getConstraints().indexOf(dest);
        getSelecionada().getConstraints().remove(selConstr);
        getSelecionada().getConstraints().add(idx, selConstr);

        btnDown2.setEnabled(selConstr != null && idx < lst.size() - 1);
        btnUP2.setEnabled(selConstr != null && idx > 0);
        PopuleLista();
    }

    public class InternalItem {

        javax.swing.JCheckBox chkPK = new javax.swing.JCheckBox();
        javax.swing.JCheckBox chkfk = new javax.swing.JCheckBox();
        javax.swing.JButton btnExcluirCampo = new javax.swing.JButton();
        javax.swing.JCheckBox chkCampo = new javax.swing.JCheckBox();
        javax.swing.JCheckBox chUnique = new javax.swing.JCheckBox();
        Campo campo = null;
    }

    ArrayList<InternalItem> Itens = new ArrayList<>();
    
    private int largura = 0;
    
    public void AdicionarPainel(Campo cmp) {
        javax.swing.JPanel ItemPan = new javax.swing.JPanel();
        java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("principal/Formularios_pt_BR");
        final int altura = 37;
        ItemPan.setSize(largura, altura);
        java.awt.FlowLayout lay = new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 10, 5);
        ItemPan.setLayout(lay);

        InternalItem item = new InternalItem();
        Itens.add(item);
        item.campo = cmp;

        javax.swing.JCheckBox chkCampo = item.chkCampo;
        javax.swing.JCheckBox chkPK = item.chkPK;
        javax.swing.JCheckBox chkfk = item.chkfk;
        javax.swing.JButton btnExcluir = item.btnExcluirCampo;
        javax.swing.JCheckBox chUnique = item.chUnique;

        chkCampo.setText(cmp.getTexto()); // NOI18N
        chkCampo.setPreferredSize(new Dimension(120, 23));
        ItemPan.add(chkCampo);

        chkPK.setText(bundle.getString("EditorDeIR.chkPK")); // NOI18N
        chkPK.setSize(new Dimension(97, 23));
        ItemPan.add(chkPK);

        chkfk.setText(bundle.getString("EditorDeIR.chkFK")); // NOI18N
        chkfk.setSize(new Dimension(115, 23));
        ItemPan.add(chkfk);

        chUnique.setText(bundle.getString("EditorDeIR.chkUNIQUE")); // NOI18N
        chUnique.setSize(new Dimension(51, 23));
        ItemPan.add(chUnique);

        btnExcluir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/excluir.png"))); // NOI18N
        btnExcluir.setToolTipText(bundle.getString("EditorDeCampos.tooltip.excluir")); // NOI18N
        btnExcluir.setPreferredSize(new Dimension(49, 25));
        ItemPan.add(btnExcluir);

        Principal.add(ItemPan);
        if (largura == 0) {
            largura = lay.preferredLayoutSize(ItemPan).width;
        }
        ItemPan.setBounds(0, v, largura, altura);
        v += altura + 3;
        Principal.setPreferredSize(new Dimension(largura, v));
        
        chkCampo.setSelected(false);
        chkfk.setSelected(cmp.isFkey());
        chkPK.setSelected(cmp.isKey());
        chUnique.setSelected(cmp.isUnique());
        chUnique.setEnabled(false);
        chUnique.setToolTipText(Editor.fromConfiguracao.getValor("Inspector.dica.campo.unique"));

        chkCampo.setEnabled(getSelConstr() != null);
        
        chkfk.addItemListener((java.awt.event.ItemEvent evt) -> {
            if (populando) {
                return;
            }
            if (cmp.isFkey() != chkfk.isSelected()) {
                cmp.setFkey(chkfk.isSelected());
                cmp.getTabela().DoMuda();
                cmp.InvalidateArea();
                Done();
            }
        });

        chkPK.addItemListener((java.awt.event.ItemEvent evt) -> {
            if (populando) {
                return;
            }
            if (cmp.isKey() != chkPK.isSelected()) {
                cmp.setKey(chkPK.isSelected());
                cmp.getTabela().DoMuda();
                cmp.InvalidateArea();
                Done();
            }
        });

        chkCampo.addItemListener((java.awt.event.ItemEvent evt) -> {
            if (getSelConstr() == null || populando) {
                return;
            }
            cmp.SetUnique(chkCampo.isSelected(), getSelConstr());
            boolean bkp = populando;
            populando = true;
            chUnique.setSelected(cmp.isUnique());
            populando = bkp;
            cmp.getTabela().DoMuda();
            cmp.InvalidateArea();
            Done();
        });

        btnExcluir.addActionListener((java.awt.event.ActionEvent evt) -> {
            cmp.getTabela().RemoveCampo(cmp);
            InternalItem itemdel = Itens.stream().filter(it -> it.campo == cmp).findAny().orElse(null);
            Itens.remove(itemdel);
            ItemPan.setEnabled(false);
            chkCampo.setEnabled(false);
            chkPK.setEnabled(false);
            chUnique.setEnabled(false);
            chkfk.setEnabled(false);
            btnExcluir.setEnabled(false);
            ItemPan.setBackground(Color.lightGray);
            Done();
        });

        ItemPan.validate();
        Principal.validate();
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton Adicionar;
    private javax.swing.JList<String> Listador;
    private javax.swing.JPanel Principal;
    private javax.swing.JButton btnAdd;
    private javax.swing.JButton btnDel;
    private javax.swing.JButton btnDown2;
    private javax.swing.JButton btnPronto;
    private javax.swing.JButton btnUP2;
    private javax.swing.JCheckBox chkIsnomeada;
    private javax.swing.JComboBox<String> comboTabelas;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JToolBar.Separator jSeparator7;
    private javax.swing.JToolBar.Separator jSeparator8;
    private javax.swing.JToolBar.Separator jSeparator9;
    private javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JToolBar jToolBar3;
    private javax.swing.JTextArea mostrador;
    private javax.swing.JTextField txtNome;
    // End of variables declaration//GEN-END:variables

    DiagramaLogico diagrama = null;
    List<Tabela> tabelas = null;

    public void Inicie(DiagramaLogico diag) {
        diagrama = diag;
        comboTabelas.removeAllItems();
        tabelas = diagrama.getListaDeTabelas();
        Tabela sel = (diag.getSelecionado() instanceof Tabela ? (Tabela) diag.getSelecionado() : null);
        int idx = 0;
        for (int i = 0; i < tabelas.size(); i++) {
            Tabela t = tabelas.get(i);
            comboTabelas.addItem(String.valueOf(i + 1) + " - " + t.getTexto());
            if (t == sel) {
                idx = i;
            }
        }
        sel = tabelas.get(idx);

        comboTabelas.setSelectedIndex(idx);

        comboTabelas.addItemListener((ItemEvent e) -> {
            if (e.getStateChange() == ItemEvent.SELECTED) {
                setSelecionada(tabelas.get(comboTabelas.getSelectedIndex()));
            }
        });

        Listador.addListSelectionListener(new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent arg) {
                if (!arg.getValueIsAdjusting()) {
                    List<Constraint> lst = getSelecionada().getConstraints().stream().filter(c -> c.getTipo() == Constraint.CONSTRAINT_TIPO.tpUNIQUE).collect(Collectors.toList());
                    if (lst.size() > Listador.getSelectedIndex() && Listador.getSelectedIndex() > -1) {
                        Constraint tmp = lst.get(Listador.getSelectedIndex());
                        setSelConstr(tmp);
                    }
                }
            }
        });

        setSelecionada(sel);

        txtNome.addKeyListener(new KeyListener() {
            @Override
            public void keyTyped(KeyEvent e) {
            }

            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
                    Constraint pk = getSelConstr();
                    if (pk == null) {
                        return;
                    }
                    txtNome.setText(pk.getNome());
                } else if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                    DoneTexto();
                }
            }

            @Override
            public void keyReleased(KeyEvent e) {
            }
        });

        chkIsnomeada.addItemListener((java.awt.event.ItemEvent evt) -> {
            if (populando) {
                return;
            }
            DoneTexto();
        });

        chkIsnomeada.addActionListener((java.awt.event.ActionEvent evt) -> {
            if (populando) {
                return;
            }
            DoneTexto();
        });
    }

    private Constraint selConstr = null;

    public Constraint getSelConstr() {
        return selConstr;
    }

    public void setSelConstr(Constraint selConstr) {
        if (this.selConstr != selConstr) {
            SetSelConstr(selConstr);
        }
    }

    private boolean populando = false;

    public void SetSelConstr(Constraint selConstr) {
        populando = true;
        this.selConstr = selConstr;
        Itens.stream().forEach(item -> {
            item.chkCampo.setEnabled(selConstr != null);
            item.chkCampo.setSelected(false);
            item.chUnique.setSelected(false);
        });
        btnDel.setEnabled(selConstr != null);
        List<Constraint> lst = getSelecionada().getConstraints().stream().filter(c -> c.getTipo() == Constraint.CONSTRAINT_TIPO.tpUNIQUE).collect(Collectors.toList());
        int ix = selConstr != null ? lst.indexOf(selConstr) : -1;
        btnDown2.setEnabled(selConstr != null && ix < lst.size() - 1);
        btnUP2.setEnabled(selConstr != null && ix > 0);
        if (selConstr != null) {
            Itens.stream().forEach(item -> {
                if (selConstr.getCamposDeOrigem().indexOf(item.campo) > -1) {
                    item.chkCampo.setSelected(true);
                }
                item.chUnique.setSelected(item.campo.isUnique());
            });
        }
        if (getSelecionada().isSelecionado() && getSelecionada().getConstraintSelecionado() != selConstr) {
            getSelecionada().setConstraintSelecionado(selConstr);
            getSelecionada().getMaster().PerformInspector();
        }
        Done();
        populando = false;
    }

    private Tabela selecionada = null;

    public Tabela getSelecionada() {
        return selecionada;
    }

    public void setSelecionada(Tabela selecionada) {
        if (this.selecionada != selecionada) {
            this.selecionada = selecionada;
            Popule(selecionada);
        }
    }

    private void Popule(Tabela sel) {
        Principal.removeAll();
        Principal.validate();
        Itens.clear();
        v = 0;
        sel.getCampos().stream().forEach(c -> AdicionarPainel(c));
        Principal.repaint();
        PopuleLista();
    }

    private void PopuleLista() {
        List<Constraint> uni = getSelecionada().getConstraints().stream().filter(c -> c.getTipo() == Constraint.CONSTRAINT_TIPO.tpUNIQUE).collect(Collectors.toList());
        DefaultListModel lst = new DefaultListModel();
        int t = 1;
        for (Constraint contr : uni) {
            lst.addElement(Integer.toString(t++) + " - " + contr.getNomeFormatado());
        }
        Listador.setModel(lst);
        if (lst.isEmpty()) {
            SetSelConstr(null);
        } else {
            int idx = (getSelecionada().getConstraintSelecionado() == null) ? 0 : uni.indexOf(getSelecionada().getConstraintSelecionado());
            Listador.setSelectedIndex(idx);
        }
    }
}
