/*
 * 文件名：CronExpresUtil.java
 * 版权：亚信联创版权所有
 * 描述：TODO
 * 修改人：xuwei3
 * 修改时间：2013-12-30
 * 修改内容：TODO
 */
package com.ozs.da.utils;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import com.ozs.da.constant.Constant;
import org.quartz.CronExpression;
import org.quartz.CronTrigger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @description TODO
 * @author [xuwei3]
 * @version [版本号,2013-12-30]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
public class CronExpresUtil
{
	private static final Logger logger = LoggerFactory.getLogger(CronExpresUtil.class);
	private static final List<Integer> JOB_PERIOD_TYPE = new ArrayList<Integer>();
	static
	{
		JOB_PERIOD_TYPE.add(Constant.JOB_PERIOD_SECONDS);
		JOB_PERIOD_TYPE.add(Constant.JOB_PERIOD_MINUTE);
		JOB_PERIOD_TYPE.add(Constant.JOB_PERIOD_HOUR);
		JOB_PERIOD_TYPE.add(Constant.JOB_PERIOD_DAY);
		JOB_PERIOD_TYPE.add(Constant.JOB_PERIOD_MONTH);
		JOB_PERIOD_TYPE.add(Constant.JOB_PERIOD_WEEK);
		JOB_PERIOD_TYPE.add(Constant.JOB_PERIOD_YEAR);
	}

	/**
	 * 
	 * @description 获取job下一次运行时间
	 * @param cronexpressions
	 *            job对应cron表达式
	 * @param date
	 *            本次运行时间
	 * @return
	 */
	public static Date getNextFiredTime(List<CronExpression> cronexpressions, Date date)
	{
		if (null == cronexpressions || cronexpressions.size() == 0)
		{
			logger.warn("Job对应的CRON表达式为空，请确认job配置正确");
			return null;
		}
		Iterator<CronExpression> ite = cronexpressions.iterator();
		Date result = null;
		Date nextFiretime = null;
		CronExpression cronExp = null;
		while (ite.hasNext())
		{
			cronExp = ite.next();
			nextFiretime = cronExp.getTimeAfter(date);
			if (null != nextFiretime)
			{
				result = (null == result ? nextFiretime : (nextFiretime.before(result) ? nextFiretime : result));
			}
		}
		return result;
	}

	public static Date getNextFiredTime(Set<CronTrigger> triggers, Date date)
	{
		if (triggers.size() == 0)
		{
			logger.warn("Job对应的CRON表达式为空，请确认job配置正确");
			return null;
		}
		Iterator<CronTrigger> ite = triggers.iterator();
		Date result = null;
		Date nextFiretime = null;
		CronTrigger trigger = null;
		while (ite.hasNext())
		{
			trigger = ite.next();
			nextFiretime = trigger.getFireTimeAfter(date);
			if (null != nextFiretime)
			{
				result = (null == result ? nextFiretime : (nextFiretime.before(result) ? nextFiretime : result));
			}
		}
		return result;
	}

	/**
	 * 
	 * @description 判断给出的cron时候满足cron表达式规范
	 * @param cronExpression
	 *            需要判断的cron表达式
	 * @return
	 */
	public static boolean isValidExpress(String cronExpression)
	{
		return CronExpression.isValidExpression(cronExpression);
	}

	/**
	 * 
	 * @description 判断给出的时间是否满足cron
	 * @param cronexpressions
	 *            cron表达式
	 * @param compareDate
	 *            判断时间，为空则默认是当前时间
	 * @return
	 */
	public static boolean isSatisRunCondition(List<CronExpression> cronexpressions, Date compareDate)
	{
		if (cronexpressions.size() == 0)
		{
			logger.warn("Job对应的CRON表达式为空，请确认job配置正确");

			return false;
		}
		if (null == compareDate)
		{
			compareDate = new Date();
		}
		for (CronExpression cronexp : cronexpressions)
		{
			if (cronexp.isSatisfiedBy(compareDate))
			{
				logger.info("给出的时间满足cron，达到运行时间::" + compareDate);
				return true;
			}
		}
		logger.info("给出的时间不满足cron，未达到运行条件");
		return false;
	}

	public static int getPeriodType(String cronExp) throws ParseException
	{
		String[] periods = cronExp.split(" ");
		if (periods.length != 7)
		{
			throw new ParseException("CRON表达式长度异常", -1);
		}
		for (int i = 0; i < 7; i++)
		{
			if (!"*".equals(periods[i]))
			{
				return JOB_PERIOD_TYPE.get(i);
			}
		}
		return -1;
	}

	public static int getPeriodinterval(String cronExp) throws ParseException
	{
		String[] periods = cronExp.split(" ");
		if (periods.length != 7)
		{
			throw new ParseException("CRON表达式长度异常", -1);
		}
		for (int i = 0; i < 7; i++)
		{
			if (!"*".equals(periods[i]))
			{
				return Integer.parseInt(periods[i]);
			}
		}
		return -1;
	}
}
