/**
 * ScheduleTimeline.java
 * Created Jun 9, 2008
 * Copyright (c) TANDBERG Television 2007-2008
 */
package com.tandbergtv.watchpoint.pmm.web.schedule;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.GregorianCalendar;

import com.tandbergtv.watchpoint.pmm.entities.Schedule;
import com.tandbergtv.watchpoint.pmm.schedule.notify.IScheduleNotifier;
import com.tandbergtv.workflow.core.service.ServiceRegistry;

/**
 * A timeline for a partner or service that contains schedules for a date range
 * 
 * @author Sahil Verma
 */
public class ScheduleTimeline {
	
	private String name;
	
	private Collection<Schedule> schedules;
	
	private Date month;
	
	private Long id;
	
	/**
	 * Creates a ScheduleTimeline
	 */
	protected ScheduleTimeline() {
		this.schedules = new ArrayList<Schedule>();
	}

	/**
	 * Creates a ScheduleTimeline
	 * @param name
	 */
	public ScheduleTimeline(Long id, String name, Date month) {
		this();
		this.id = id;
		this.name = name;
		this.month = month;
	}

	/**
	 * @return the id
	 */
	public Long getId() {
		return this.id;
	}

	/**
	 * @return the name
	 */
	public String getName() {
		return this.name;
	}

	/**
	 * @param name the name to set
	 */
	public void setName(String name) {
		this.name = name;
	}
	
	/**
	 * Adds the specified schedule
	 * 
	 * @param schedule
	 */
	public void addSchedule(Schedule schedule) {
		this.schedules.add(schedule);
	}
	
	/**
	 * Returns the display string for the month
	 * @return
	 */
	public Collection<TimelineEntry> getEntries() {
		Collection<TimelineEntry> entries = new ArrayList<TimelineEntry>();
		Calendar calendar = new GregorianCalendar();
		IScheduleNotifier service = ServiceRegistry.getDefault().lookup(IScheduleNotifier.class);
		
		calendar.setTime(this.month);
		
		int min = calendar.getActualMinimum(Calendar.DAY_OF_MONTH);
		int max = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
		
		/* This is neither space nor time efficient but I don't care at this point */
		for (int i = min; i <= max; i++) {
			TimelineEntry entry = null;
			
			for (Schedule schedule : this.schedules) {
				if (schedule.getDate().compareTo(calendar.getTime()) == 0) {
					entry = new TimelineEntry(schedule.getId().toString(), schedule.getType());
					
					if (service.getNotification(schedule) != null)
						entry.setIsAlert(true);
					
					break;
				}
			}
			
			/* Make sure there is a blank entry per day */
			if (entry == null)
				entry = new TimelineEntry();
			
			entries.add(entry);
			
			calendar.roll(Calendar.DATE, 1);
		}
		
		return entries;
	}

	/* (non-Javadoc)
	 * @see java.lang.Object#toString()
	 */
	public String toString() {
		return this.name;
	}
}
