package com.ronald.gantengtimesheet.ui.timesheet;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.swing.table.DefaultTableModel;
import com.ronald.gantengtimesheet.db.RecordEntity;
import com.ronald.gantengtimesheet.db.RecordEntityCollection;
@SuppressWarnings("serial")
public class TimesheetTableModel extends DefaultTableModel {
protected static enum Columns {
NO ("No", 40, Integer.class),
DURATION ("Duration (hr)", 80, Double.class),
RATE ("Rate", 80, Double.class),
DESCRIPTION("Description", 200, String.class),
;
private final String name;
private final int width;
private final Class<?> clazz;
Columns(final String name, final int width, final Class<?> clazz) {
this.name = name;
this.width = width;
this.clazz = clazz;
}
public String getName() {
return name;
}
public int getWidth() {
return width;
}
public Class<?> getClazz() {
return clazz;
}
}
private RecordEntity newRecord = new RecordEntity();
protected List<RecordEntity> data = new ArrayList<RecordEntity>();
@Override
public int getColumnCount() {
return Columns.values().length;
}
@Override
public String getColumnName(int column) {
return Columns.values()[column].getName();
}
@Override
public int getRowCount() {
if (data == null) return 0;
return data.size()+1;
}
@Override
public Object getValueAt(int row, int column) {
final Columns col = Columns.values()[column];
final RecordEntity e = row < data.size() ? data.get(row) : null;
if (e == null) {
switch (col) {
case NO: return null;
case DURATION: {
double sum=0.0;
for (RecordEntity entity : data) {
if (!entity.isNew()) {
sum+=entity.getDuration();
}
}
return sum;
}
case RATE: return null;
case DESCRIPTION: return null;
}
} else {
switch (col) {
case NO: return row+1;
case DURATION: return e.getDuration();
case RATE: return e.getRate();
case DESCRIPTION: return e.getDescription();
}
}
return null;
}
@Override
public void setValueAt(Object val, int row, int column) {
final Columns col = Columns.values()[column];
final RecordEntity e = data.get(row);
switch(col) {
case DURATION: {
try {
e.setDuration(Double.valueOf((String) val));
} catch (NumberFormatException ex) {
e.setDuration(null);
}
break;
}
case RATE: {
try {
e.setRate(Double.valueOf((String)val));
} catch (NumberFormatException ex) {
e.setRate(null);
}
break;
}
case DESCRIPTION: {
e.setDescription((String) val);
break;
}
}
if (e.canSave()) {
e.setDate(TimesheetComponent.getInstance().getSelectedDate());
e.setUpdated(new Date());
if (e.isNew()) {
e.save();
newRecord = new RecordEntity();
data.add(newRecord);
} else {
e.save();
}
}
}
@Override
public boolean isCellEditable(int row, int column) {
return column != Columns.NO.ordinal();
}
public void reload() {
List<RecordEntity> result = RecordEntityCollection.getInstance().getRecordEntities(TimesheetComponent.getInstance().getSelectedDate());
if (!newRecord.isNew()) {
newRecord = new RecordEntity();
}
result.add(newRecord); // add last row
data = result;
}
}