package app.database.model.note;
import java.util.ArrayList;
import java.util.List;
import org.ytreza.data.Filter;
import org.ytreza.data.origin.Origin;
import app.database.model.ModelName;
import app.database.model.tag.ModelTag;
import app.database.model.tagAndNote.TableTagForNote;
import app.database.model.tagAndNote.ModelTagAndNote;
import org.ytreza.data.table.Table;
import org.ytreza.data.table.TableFactory;
import org.ytreza.data.table.exception.ItemException;
import org.ytreza.data.table.exception.UnableToSaveException;
public class NoteOrigin extends Origin<ModelNote>{
public NoteOrigin(Table<ModelNote> table, TableFactory factory, int id, ModelNote item) {
super(table, factory, id, item);
}
@Override
protected void doBeforeDelete() {
// removeAllTag();
}
@Override
protected void doAfterSave() {
// saveTag();
}
private void saveTag(){
removeAllTag();
saveTagList();
}
private void removeAllTag() {
try {
Table<ModelTagAndNote> tableNoteAndTag = (TableTagForNote) getFactory().getTable(ModelName.NOTE_TAG);
Filter filter = new Filter();
filter.add(ModelTagAndNote.NAME_OBJECT_ID, getId());
tableNoteAndTag.deleteItem(filter);
} catch (ItemException e) {
// AUTO_TODO Auto-generated catch block
e.printStackTrace();
}
}
private void saveTagList() {
for (ModelTagAndNote tagAndNote : getTagAndNoteList()) {
saveTagAndNote(tagAndNote);
}
}
private List<ModelTagAndNote> getTagAndNoteList() {
TableTagForNote table = (TableTagForNote) getFactory().getTable(ModelName.NOTE_TAG);
List<ModelTagAndNote> result = new ArrayList<ModelTagAndNote>();
List<ModelTag> officialList = getItem().getOfficialTagList();
for (ModelTag tag : getItem().getTagList()) {
if (officialList.contains(tag)) {
result.add(table.createItem(new ModelTagAndNote(tag,getItem(),true)));
} else {
result.add(table.createItem(new ModelTagAndNote(tag,getItem(),false)));
}
}
return result;
}
private void saveTagAndNote(ModelTagAndNote tagAndNote){
try {
tagAndNote.save();
} catch (ItemException e) {
// AUTO_TODO Auto-generated catch block
e.printStackTrace();
} catch (UnableToSaveException e) {
// AUTO_TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void doAfterGetItem() {
// List<ModelTag> list ;
//
// TableTag tableTag = (TableTag) getFactory().getTable(ModelName.TAG);
//
// String commandString = "select distinct tag_id as id";
// commandString += " from note_tag";
// commandString += " where object_id = " + getId() + " and official = 1";
// try {
// list = tableTag.getItem(new JdbcCommand(commandString));
// } catch (Exception e) {
// list = new ArrayList<ModelTag>();
// e.printStackTrace();
// }
// getItem().setTagList(list);
}
}