/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache license, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.internna.iwebmvc.parsers;
import java.util.ArrayList;
import java.util.List;
import org.internna.iwebmvc.dao.DAO;
import org.internna.iwebmvc.model.Poll;
import org.internna.iwebmvc.model.PollOption;
import org.internna.iwebmvc.model.UUID;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;
/**
* Parses @{@link Poll} entities.
*
* @author Jose Noheda
* @since 2.0
*/
public class PollParser extends AbstractEntityParser<Poll> {
public PollParser(DAO dao) {
super(Poll.class, dao);
}
@Override
public Poll parse(Poll poll) {
if (poll != null) {
if (poll.getId() != null) {
return parseExistingPoll(poll);
} else if (!CollectionUtils.isEmpty(poll.getOptions())) {
for (PollOption option : poll.getOptions())
if (option.getPoll() == null)
option.setPoll(poll);
}
}
return poll;
}
protected Poll parseExistingPoll(Poll poll) {
Poll old = getDao().find(Poll.class, poll.getId());
BeanUtils.copyProperties(poll, old, new String[]{"id", "question", "options"});
if (poll.getQuestion() != null)
for (int index = 0; index < poll.getQuestion().getData().size(); index++)
old.getQuestion().getData().get(index).setTranslation(poll.getQuestion().getData().get(index).getTranslation());
else old.setQuestion(null);
if (CollectionUtils.isEmpty(poll.getOptions())) old.clearOptions();
else {
for (PollOption option : poll.getOptions()) {
if (option.getId() != null) {
for (PollOption oldPollOption : old.getOptions()) {
if (oldPollOption.getId().equals(option.getId())) {
oldPollOption.setOrder(option.getOrder());
for (int answerIndex = 0; answerIndex < oldPollOption.getAnswer().getData().size(); answerIndex++)
oldPollOption.getAnswer().getData().get(answerIndex).setTranslation(option.getAnswer().getData().get(answerIndex).getTranslation());
}
}
} else old.addOption(option);
}
List<PollOption> removed = new ArrayList<PollOption>();
for (PollOption option : old.getOptions()) {
boolean remove = true;
for (PollOption newOption : poll.getOptions()) {
UUID oid = option.getId(), nid = newOption.getId();
remove &= oid != null;
if (remove && (option.getId().equals(nid)))
remove = false;
}
if (remove) removed.add(option);
}
for (PollOption remove : removed) old.removeOption(remove);
}
return old;
}
}