package com.tandbergtv.watchpoint.pmm.job;

import java.util.ArrayList;
import java.util.List;

import com.tandbergtv.cms.rules.service.IRuleService;
import com.tandbergtv.cms.rules.service.RuleServiceStatus;
import com.tandbergtv.watchpoint.pmm.entities.Job;

public class JobRulesetManager implements IRuleService {

	public RuleServiceStatus canDelete(long ruleSetId) {
		String jobNames = getJobNames(ruleSetId);

		if (jobNames == null) {
			return new RuleServiceStatus(true);
		} else {
			List<String> parameters = new ArrayList<String>();
			parameters.add(String.valueOf(ruleSetId));
			parameters.add(jobNames);
			return new RuleServiceStatus(false, "errJobIsSecheduledCantDelete",
					parameters);
		}
	}

	@Override
	public RuleServiceStatus canRemoveSchedulable(long ruleSetId) {
		String jobNames = getJobNames(ruleSetId);

		if (jobNames == null) {
			return new RuleServiceStatus(true);
		} else {
			return new RuleServiceStatus(false,
					"errJobIsSecheduledNeedSchedulable", jobNames);
		}
	}

	/*
	 * Returns a comma delimited list of job names associate with the ruleSetId
	 * or null if there are none associated.
	 */
	private String getJobNames(long ruleSetId) {
		List<Job> jobs = JobManager.getInstance().getAllJobs(
				String.valueOf(ruleSetId));

		if (jobs == null || jobs.size() == 0) {
			return null;
		}

		StringBuffer result = new StringBuffer("");
		for (Job job : jobs) {
			if (!result.toString().isEmpty()) {
				result.append(", ");
			}
			result.append(job.getName());
		}
		return result.toString();
	}
}