package com.tandbergtv.watchpoint.pmm.schedule;

import java.util.ArrayList;
import java.util.List;

import com.tandbergtv.watchpoint.pmm.core.ITitleValidationService;
import com.tandbergtv.watchpoint.pmm.core.TitleValidationMessage;
import com.tandbergtv.watchpoint.pmm.core.TitleValidationMessage.Type;
import com.tandbergtv.watchpoint.pmm.entities.IAssetList;
import com.tandbergtv.watchpoint.pmm.entities.Schedule;
import com.tandbergtv.watchpoint.pmm.entities.Title;
import com.tandbergtv.watchpoint.pmm.entities.TitleListType;
import com.tandbergtv.watchpoint.pmm.title.conf.IRightsManager;
import com.tandbergtv.watchpoint.pmm.title.conf.specs.RightsManagerFactory;
import com.tandbergtv.workflow.core.service.ServiceRegistry;

/**
 * If the title asked to validate is present in any schedule, then checks if the
 * license end date is valid for that schedule. If not then adds a validation
 * error message and returns that list.
 * 
 * @author spuranik
 * 
 */
public class ScheduleTitleValidator implements ITitleValidationService {

	private String INVALID_LICENSE_DATE = "INVALID_LICENSE_DATE";
	
	@Override
	public List<TitleValidationMessage> validate(Title title, boolean isDraft) {
		// Performs the validation irrespective of whether its being saved as draft or not. 
		
		// If this title is not associated with any kind of lists, its valid
		if(title.getTitlelists().isEmpty()) {
			return new ArrayList<TitleValidationMessage>();
		}
		
		IRightsManager rm = RightsManagerFactory.getRightsManager();
		ISchedulePersistenceService scheduleService = ServiceRegistry
				.getDefault().lookup(ISchedulePersistenceService.class);

		List<TitleValidationMessage> errors = new ArrayList<TitleValidationMessage>();
		// Prepares a validation error for all violating schedules
		for(IAssetList list : title.getTitlelists()) {
			if(list.getType() == TitleListType.PITCH) {
				Schedule schedule = scheduleService.get(list.getId());
				if (rm != null && !rm.isLicensed(title, schedule.getDate())) {
					String message = "Title is not licensed for schedule: " + schedule.getId();
					errors.add(new TitleValidationMessage(message, Type.Error, INVALID_LICENSE_DATE));
				}
			}
		}
		return errors;
	}
}
