package opencm.domain.service; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.Stack; import opencm.domain.interfaces.ConsultaRepository; import opencm.domain.model.Consulta; import opencm.domain.model.HorarioAtendimento; import org.joda.time.Interval; public final class AgendamentoService { private ConsultaRepository consultaRepository; public AgendamentoService(ConsultaRepository consultaRepository) { this.consultaRepository = consultaRepository; } private List consultaIntervals(List consultas) { List result = new ArrayList(); for (Consulta consulta : consultas) { result.add(new Interval(consulta.getInicio(), consulta.getDuracao())); } return mergeIntervals(result); } private List atendimentoIntervals(List horarios) { List result = new ArrayList(); for (HorarioAtendimento horario : horarios) { result.add(new Interval(horario.getHoraInicial().toDateTimeToday(), horario.getHoraFinal().toDateTimeToday())); } return mergeIntervals(result); } private List mergeIntervals(List intervals) { List sortedIntervals = new ArrayList(intervals); Collections.sort(sortedIntervals, new Comparator() { public int compare(Interval a, Interval b) { return a.getStart().compareTo(b.getStart()); }}); Iterator sortedIntervalsIt = sortedIntervals.iterator(); Stack mergedIntervals = new Stack(); while (sortedIntervalsIt.hasNext()) { Interval current = sortedIntervalsIt.next(); if (!mergedIntervals.empty() && current.abuts(mergedIntervals.peek())) { mergedIntervals.push(new Interval(mergedIntervals.pop().getStart(), current.getEnd())); } else { mergedIntervals.push(current); } } return mergedIntervals; } }