/* Copyright (c) 1993 by Sanjay Ghemawat */
#include "collect.h"
#include "cal_tcl.h"
#include "item_tcl.h"

#include "calfile.h"
#include "calendar.h"
#include "dateset.h"
#include "item.h"

implementArray(Occurrences,Occurrence)

void collect_occurrences(Occurrences& list, Date s, Date f, int e) {
    Calendar_Tcl* cal = calendar_instance;

    list.clear();
    for (int i = 0; i <= cal->includes->size(); i++) {
	Calendar* calendar;
	if (i >= cal->includes->size()) {
	    calendar = cal->main->GetCalendar();
	}
	else {
	    calendar = cal->includes->slot(i)->GetCalendar();
	}

	for (int j = 0; j < calendar->Size(); j++) {
	    Item_Tcl* item = Item_Tcl::find(calendar->Get(j));
	    if (item == 0) {
		continue;
	    }

	    Date d = s - 1;
	    Date limit = f;
	    if (e) {
		limit += item->value()->GetRemindStart();
	    }

	    while (item->value()->Dates()->next(d, d) && (d <= limit)) {
		Occurrence o;
		o.item = item;
		o.date = d;
		list.append(o);
	    }
	}
    }
}

static int occurs_before(Occurrence const& x, Occurrence const& y) {
    if (x.date < y.date) return 1;
    if (x.date > y.date) return 0;

    Appointment* xa = x.item->value()->AsAppointment();
    Appointment* ya = y.item->value()->AsAppointment();

    int xs = (xa == 0) ? -1 : xa->GetStart();
    int ys = (ya == 0) ? -1 : ya->GetStart();

    return (xs < ys);
}

void sort_occurrences(Occurrences& list) {
    int i = 0;
    while (i < list.size()) {
	/* Find min element in list[i..] */
	int minIndex = i;

	for (int j = i+1; j < list.size(); j++) {
	    if (occurs_before(list[j], list[minIndex])) {
		minIndex = j;
	    }
	}

	Occurrence temp;
	temp = list[i];
	list[i] = list[minIndex];
	list[minIndex] = temp;

	i++;
    }
}
