return false;
}
// find the message before
final Key sceneKey = Scene.createKey(campaignKey, sceneId);
final Scene scene = dao.readScene(context, sceneKey);
if(scene == null) {
logger.severe("Scene not found " + sceneKey);
context.addError(Errors.NOT_FOUND_SCENE, sceneKey);
return false;
}
final Key messageBeforeKey = Message.createKey(sceneKey, messageBeforeId);
final Message messageBefore = dao.readMessage(context, messageBeforeKey);
if(messageBefore == null) {
logger.severe("Message not found " + messageBeforeKey);
context.addError(Errors.NOT_FOUND_MESSAGE, messageBeforeKey);
return false;
}
final Transaction tx = dao.beginTransaction();
try {
final long newIndex;
// find the message after
final Key messageAfterKey = messageBefore.getNext();
final Message messageAfter;
if(messageAfterKey != null) {
messageAfter = dao.readMessage(context, messageAfterKey);
if(messageAfter == null) {
logger.severe("Message not found " + messageAfterKey);
context.addError(Errors.NOT_FOUND_MESSAGE, messageAfterKey);
return false;
}
newIndex = (messageBefore.getIndex() + messageAfter.getIndex()) / 2;
if(newIndex == messageBefore.getIndex()
|| newIndex == messageAfter.getIndex()) {
logger.severe("No more indexes to insert between "
+ messageBeforeKey + " and " + messageAfterKey);
context.addError(Errors.IMPOSSIBLE, "index");
return false;
}
} else {
newIndex = getNewMessageIndex(messageBefore.getIndex());
messageAfter = null;
}
final Message message = new Message(scene);
message.setDate(new Date());
message.setType(MessageType.OFF.getCode());
message.setPrevious(messageBeforeKey);
message.setContent(content);
message.setIndex(newIndex);
if(messageAfter != null) {
message.setNext(messageAfterKey);
}
dao.save(context, message);
messageBefore.setNext(message);
dao.save(context, messageBefore);
if(messageAfter != null) {
messageAfter.setPrevious(message);
dao.save(context, messageAfter);
} else {
scene.setLastMessage(message);
dao.save(context, scene);
}
tx.commit();