/**
 * TimerHelper.java
 * Created on Jul 3, 2008
 * (C) Copyright TANDBERG Television Ltd.
 */
package com.tandbergtv.watchpoint.pmm.job.timers;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;

import com.tandbergtv.watchpoint.pmm.entities.RuleParameter;
import com.tandbergtv.watchpoint.pmm.entities.RuleParameterDataType;
import com.tandbergtv.watchpoint.pmm.entities.RuleTypeParameter;
import com.tandbergtv.watchpoint.pmm.job.ui.JobUIConstants;

/**
 * This class contains all shared methods used by various timer representation classes.
 * 
 * @author spuranik
 * 
 */
public class TimerHelper {

	
	private static String DEFAULT_TIME = "12:00 am";
	private static final Logger logger = Logger.getLogger(TimerHelper.class);

	/**
	 * Determines the order of the required parameter type from the given rule type and returns the
	 * value from the job rule parameter value with that order.
	 * 
	 * @param ruleTypeParams
	 * @param params
	 * @return
	 */
	public static String getParameter(List<RuleTypeParameter> ruleTypeParams,
			List<RuleParameter> params, RuleParameterDataType type) {

		for (RuleTypeParameter parameter : ruleTypeParams) {
			if (parameter.getType() == type) {
				for (int i = 0; i < params.size(); i++) {
					if (params.get(i).getOrder() == parameter.getOrder()) {
						return params.get(i).getValue();
					}
				}
			}
		}
		return null;
	}

	/**
	 * This method sets the given time for the date specified
	 * 
	 * @param date
	 * 	Date for which the time will be set
	 * @param time
	 * 	Time that will be set for the date
	 * @return
	 * 	the given date which has the specified time. If there was an error
	 * 	while setting the time, the original date is returned back.
	 */
	public static Date getStartDateTime(Date date, String time) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);

		if (time == null || time.trim().length() < 0) {
			time = DEFAULT_TIME;
		}

		try {
			SimpleDateFormat sf = new SimpleDateFormat(JobUIConstants.JOB_RULE_TIME_FORMAT);
			sf.setLenient(false);
			Date dt = sf.parse(time);

			Calendar tc = Calendar.getInstance();
			tc.setTime(dt);
			// set the hour and minute in the date given
			c.set(Calendar.HOUR_OF_DAY, tc.get(Calendar.HOUR_OF_DAY));
			c.set(Calendar.MINUTE, tc.get(Calendar.MINUTE));
			c.set(Calendar.SECOND, 0);

			return c.getTime();
		} catch (ParseException e) {
			logger.error("Error while setting time in date: " + e.toString());
			// return back the original date along with whatever time it had
			return date;
		}
	}
}
