final Collection<Long> results = findIds(useUids, session, mailbox, query);
final long[] ids = toArray(results);
final ImapResponseMessage response;
if (resultOptions == null || resultOptions.isEmpty()) {
response = new SearchResponse(ids);
} else {
IdRange[] idRanges;
List<Long> idList = new ArrayList<Long>(ids.length);
for ( int i = 0; i < ids.length; i++) {
idList.add(ids[i]);
}
List<MessageRange> ranges = MessageRange.toRanges(idList);
idRanges = new IdRange[ranges.size()];
for (int i = 0 ; i <ranges.size(); i++) {
MessageRange range = ranges.get(i);
idRanges[i] = new IdRange(range.getUidFrom(), range.getUidTo());
}
boolean esearch = false;
for (int i = 0; i < resultOptions.size(); i++) {
if (SearchResultOption.SAVE != resultOptions.get(i)) {
esearch = true;
break;
}
}
if (esearch) {
long min = -1;
long max = -1;
long count = ids.length;
if (ids.length > 0) {
min = ids[0];
max = ids[ids.length -1];
}
// Save the sequence-set for later usage. This is part of SEARCHRES
if (resultOptions.contains(SearchResultOption.SAVE)) {
if (resultOptions.contains(SearchResultOption.ALL) || resultOptions.contains(SearchResultOption.COUNT)) {
// if the options contain ALL or COUNT we need to save the complete sequence-set
SearchResUtil.saveSequenceSet(session, idRanges);
} else {
List<IdRange> savedRanges = new ArrayList<IdRange>();
if (resultOptions.contains(SearchResultOption.MIN)) {
// Store the MIN
savedRanges.add(new IdRange(min));
}
if (resultOptions.contains(SearchResultOption.MAX)) {
// Store the MAX
savedRanges.add(new IdRange(max));
}
SearchResUtil.saveSequenceSet(session, savedRanges.toArray(new IdRange[0]));
}
}
response = new ESearchResponse(min, max, count, idRanges, tag, useUids, resultOptions);
} else {
// Just save the returned sequence-set as this is not SEARCHRES + ESEARCH
SearchResUtil.saveSequenceSet(session, idRanges);
response = new SearchResponse(ids);
}
}
responder.respond(response);