/**
 * RightsManager.java
 * Created Oct 6, 2008
 * Copyright (C) Tandberg Television 2008
 */
package com.tandbergtv.watchpoint.pmm.title.conf.specs;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.tandbergtv.watchpoint.pmm.entities.Title;
import com.tandbergtv.watchpoint.pmm.title.ITitleService;
import com.tandbergtv.watchpoint.pmm.title.conf.IRightsManager;
import com.tandbergtv.workflow.core.service.ServiceRegistry;

/**
 * VOD rights manager implementation
 * 
 * @author Sahil Verma
 */
public class RightsManager implements IRightsManager {

	// NOTE: we know the xpath!
	private static String LICENSE_WINDOW_END = "/tns:Fields/tns:Rights/tns:LicensingWindowEnd";

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.tandbergtv.watchpoint.pmm.title.conf.IRightsManager#isLicensed(com
	 * .tandbergtv.watchpoint.pmm.entities.Title, java.util.Date)
	 */
	public boolean isLicensed(Title title, Date date) {
		// we really know that we are looking for title license end date which
		// is in an item under the root whose type is TITLE!
		ITitleService service = (ITitleService) ServiceRegistry.getDefault()
				.lookup(ITitleService.class);
		String endDate = com.tandbergtv.watchpoint.pmm.title.TitleUtil
				.getMetadataValue(service.getAllDecendantFields(title.getId().longValue()),
						LICENSE_WINDOW_END, "TITLE");

		// If the field was not there or the value was empty, the title is
		// invalid
		if (endDate.trim().length() == 0) {
			return false;
		}

		boolean isLicensed = false;
		try {
			Date end = new SimpleDateFormat("yyyy-MM-dd").parse(endDate);
			isLicensed = end.after(date);
		} catch (ParseException e) {
		}

		return isLicensed;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.tandbergtv.watchpoint.pmm.title.conf.IRightsManager#isLicensed(com
	 * .tandbergtv.watchpoint.pmm.entities.Title, java.util.Date,
	 * java.util.Date)
	 */
	public boolean isLicensed(Title title, Date start, Date end) {
		throw new UnsupportedOperationException("Later");
	}
}
