/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package presenter;
import business.Arvore;
import business.ContainerArvores;
import com.db4o.collections.MapEntry4;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;
import view.interfaces.IEditorView;
import view.states.arvores.Atualizacao;
import view.states.arvores.Erro;
import view.states.arvores.Inclusao;
import view.states.arvores.Navegacao;
/**
*
* @author clayton
*/
public class CenarioInventarioTableModel extends DefaultTableModel {
ContainerArvores cenario;
IEditorView view;
long lastIdArv = 0;
public CenarioInventarioTableModel(ContainerArvores pCenario, IEditorView pView) {
super(pCenario.getHeadersNames(false).toArray(), 0);
cenario = pCenario;
view = pView;
updateData();
this.addTableModelListener(createListener());
}
public List<Arvore> getUpdatedArvores() throws Exception {
List<Arvore> arvores = Collections.synchronizedList(new ArrayList<Arvore>());
Vector dv = getDataVector();
Arvore arvore = null;
for (Iterator it = dv.iterator(); it.hasNext();) {
Vector<Double> object = (Vector) it.next();
Object idArvore = object.get(0);
if (cenario.getArvoreByID((Long) idArvore) == null) {
arvore = new Arvore((Long) idArvore);
} else {
arvore = cenario.getArvoreByID((Long) idArvore);
}
for (int i = 1; i < object.size(); i++) {
String chave = getColumnName(i);
Object valor = object.get(i);
if (valor == null || valor.equals("")) {
throw new Exception("Informe um número válido");
}
if (valor instanceof Long) {
Double value = ((Long) valor).doubleValue();
arvore.put(chave, value);
} else if (valor instanceof String) {
Double value = Double.parseDouble((String) valor);
arvore.put(chave, value);
} else {
arvore.put(chave, object.get(i));
}
}
arvores.add(arvore);
}
return arvores;
}
private void updateData() {
Object[][] data = cenario.getDataAsMatrix();
setDataVector(data, view.getPresenter().getContainerArvores().getHeadersNames(false).toArray());
}
public void setContainerArvores(ContainerArvores cenario) {
this.cenario = cenario;
updateData();
}
@Override
public boolean isCellEditable(int row, int col) {
boolean hasNoFormula = cenario.getHeaderFormula(this.getColumnName(col)).equals("");
if (col > 0 && hasNoFormula) {
return true;
}
if (view.getErrors()) {
view.setState(new Erro(view));
}
return false;
}
public void addLinha() {
long codArvore = getGreaterIdArv();
addRow(new Object[]{codArvore});
view.getPresenter().getContainerArvores().addArvore(new Arvore(codArvore));
lastIdArv = codArvore;
}
public long getGreaterIdArv() {
TreeSet<Long> arvs = new TreeSet<Long>();
for (int i = 0; i < getRowCount(); i++) {
arvs.add(Long.valueOf(getValueAt(i, 0).toString()));
}
return arvs.last() + 1;
}
public Object[] getCompleteRow(int linha) {
Object[] data = new Object[getColumnCount()];
for (int i = 0; i < getColumnCount(); i++) {
if (getValueAt(linha, i) == null) {
return null;
} else {
if (i == 0) {
data[i] = getValueAt(linha, i);
} else {
data[i] = new Double(getValueAt(linha, i).toString());
}
}
}
return data;
}
@Override
public void setValueAt(Object aValue, int row, int column) {
try {
super.setValueAt(aValue, row, column);
if ((Long) getValueAt(row, 0) == lastIdArv) {
Object[] rowData = getCompleteRow(row);
if (rowData != null) {
Iterator<String> itHeader = cenario.getHeadersNames(false).iterator();
itHeader.next();
while (itHeader.hasNext()) {
String string = itHeader.next();
view.getPresenter().getContainerArvores().getArvoreByID((Long) getValueAt(row, 0)).put(string, Double.NaN);
}
view.getPresenter().getFacadeR().addDataFrameRow(row, rowData);
rowData = null;
view.setState(new Navegacao(view));
}
}
this.fireTableChanged(new TableModelEvent(this, row, row, 1, TableModelEvent.UPDATE));
} catch (Exception ex) {
Logger.getLogger(EditorPresenter.class.getName()).log(Level.SEVERE, null, ex);
}
}
private TableModelListener createListener() {
return new TableModelListener() {
@Override
public void tableChanged(TableModelEvent e) {
if (e.getType() == TableModelEvent.INSERT) {
for (int nroCol = 1; nroCol < getColumnCount(); nroCol++) {
String nomeColuna = getColumnName(nroCol);
Set<Map.Entry<String, String>> formulas = cenario.getHeaderAndFormulas();
for (Map.Entry<String, String> entry : formulas) {
String formula = entry.getValue();
String colName = entry.getKey();
if (!formula.equals("") && colName.toLowerCase().equals(nomeColuna.toLowerCase())) {
Vector rowVector = (Vector) dataVector.elementAt(getRowCount() - 1);
rowVector.setElementAt(0.0, nroCol);
}
}
}
}
if (e.getType() == TableModelEvent.UPDATE
&& !(view.getViewState() instanceof Atualizacao)
&& !(view.getViewState() instanceof Inclusao)) {
final int firstRow = e.getFirstRow();
final int lastRow = e.getLastRow();
for (int row = firstRow; row <= lastRow; row++) {
if (row >= 0) {
final int nroColun = e.getColumn();
final long codArvore = (Long) getValueAt(row, 0);
final String colName = getColumnName(nroColun);
final Double colValue = Double.parseDouble(getValueAt(row, nroColun).toString());
Map.Entry<String, Double> dado = new MapEntry4<String, Double>(colName, colValue);
cenario = view.getPresenter().getContainerArvores();
cenario.updateArvoreData(codArvore, dado);
view.getPresenter().getFacadeR().setProjeto(cenario);
view.getPresenter().getFacadeR().updateDataFrameCell(row, colValue, colName);
List<Map.Entry<String, String>> listaColunas =
Collections.synchronizedList(new ArrayList<Map.Entry<String, String>>(
cenario.getHeaderAndFormulas()));
Iterator<Map.Entry<String, String>> it = listaColunas.iterator();
synchronized (this) {
while (it.hasNext()) {
Map.Entry<String, String> header = it.next();
if (!header.getValue().equals("")) {
if (cenario != null) {
String nomeColuna = header.getKey();
String formulaColuna = header.getValue();
try {
view.setState(new Atualizacao(view));
view.getPresenter().getFacadeR().removeColumn(nomeColuna);
view.getPresenter().getFacadeR().addColumn(formulaColuna, nomeColuna);
int nroColuna = findColumn(nomeColuna);
Object[] editedColumnData = view.getPresenter().getFacadeR().getColumnasObjects(nomeColuna);
if (editedColumnData.length == dataVector.size()) {
for (int i = 0; i < editedColumnData.length; i++) {
Vector rowVector = (Vector) dataVector.elementAt(i);
rowVector.setElementAt(editedColumnData[i], nroColuna);
fireTableCellUpdated(row, nroColun);
}
}
} catch (Exception ex) {
Logger.getLogger(EditorPresenter.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
}
}
}
view.getGrid().setModel(CenarioInventarioTableModel.this);
view.getPresenter().setProjeto(view.getPresenter().getFacadeR().getCenario());
view.setState(new Navegacao(view));
}
((JFrame) view).validate();
if (view.getGrid() != null) {
view.getViewState().validaGrid();
}
}
};
}
public void addColuna(String name, Object[] data) {
addColumn(name, data);
view.getGrid().setModel(CenarioInventarioTableModel.this);
view.setColumnFormat(name);
}
}