package com.uas.search.console.b2b.schedule.model;

import java.util.Calendar;
import java.util.Date;
import java.util.Objects;

import com.uas.search.b2b.exception.SearchException;
import com.uas.search.console.b2b.schedule.service.Executable;

/**
 * 每天定时任务
 * 
 * @author sunyj
 * @since 2016年12月12日 下午3:18:42
 */
public class DailyTaskInformation extends TaskInformation {

	/**
	 * 一天的毫秒数
	 */
	private static final long MILLISECONDS_OF_ONE_DAY = 24 * 60 * 60 * 1000;

	/**
	 * 执行时间中的小时
	 */
	private int hour;

	/**
	 * 执行时间中的分钟
	 */
	private int minute;

	/**
	 * 执行时间中的秒
	 */
	private int second;

	public DailyTaskInformation(String title, Executable command, int hour, int minute, int second)
			throws SearchException {
		if (hour < 0 || hour > 23) {
			throw new SearchException("hour不合法：" + hour);
		}
		if (minute < 0 || minute > 59) {
			throw new SearchException("minute不合法：" + minute);
		}
		if (second < 0 || second > 59) {
			throw new SearchException("second不合法：" + second);
		}
		this.hour = hour;
		this.minute = minute;
		this.second = second;
		setTitle(title);
		setCommand(command);
		setInitialDelay(getInitialDelay());
		setPeriod(MILLISECONDS_OF_ONE_DAY);
	}

	public int getHour() {
		return hour;
	}

	public void setHour(int hour) {
		this.hour = hour;
	}

	public int getMinute() {
		return minute;
	}

	public void setMinute(int minute) {
		this.minute = minute;
	}

	public int getSecond() {
		return second;
	}

	public void setSecond(int second) {
		this.second = second;
	}

	@Override
	public long getInitialDelay() {
		Calendar nowCalendar = Calendar.getInstance();
		nowCalendar.setTime(new Date());
		Calendar initialDelayCalendar = (Calendar) nowCalendar.clone();
		initialDelayCalendar.set(Calendar.HOUR_OF_DAY, hour);
		initialDelayCalendar.set(Calendar.MINUTE, minute);
		initialDelayCalendar.set(Calendar.SECOND, second);
		if (initialDelayCalendar.before(nowCalendar)) {
			initialDelayCalendar.add(Calendar.DAY_OF_MONTH, 1);
		}
		return initialDelayCalendar.getTimeInMillis() - nowCalendar.getTimeInMillis();
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj) {
			return true;
		}
		if (obj == null || getClass() != obj.getClass() || !(obj instanceof DailyTaskInformation)) {
			return false;
		}
		DailyTaskInformation other = (DailyTaskInformation) obj;
		// command不好比较，不进行比较
		return Objects.equals(getTitle(), other.getTitle()) && hour == other.getHour() && minute == other.getMinute()
				&& second == other.getSecond();
	}

	@Override
	public String toString() {
		return "DailyTaskInformation [title=" + getTitle() + ", hour=" + hour + ", minute=" + minute + ", second="
				+ second + "]";
	}

}
