<?php
class Calendarista_FeedSynchJob{
	const HOOK = 'Calendarista_FeedSynchJobHook';
	public function __construct()
	{
		$generalSetting = Calendarista_GeneralSettingHelper::get();
		if($generalSetting->cronJobFeedTimeout > 0){
			$this->schedule($generalSetting->cronJobFeedTimeout);
		}
	}
	public function schedule($cronJobFeedTimeout){
		if (!self::schedulePending())
		{
			$result = wp_schedule_single_event((time() + $cronJobFeedTimeout), self::HOOK);
		}
	}
	public static function init(){
		Calendarista_FeedHelper::synchronizeAllFeeds();
	}
	public static function register(){
		add_action(self::HOOK, array('Calendarista_FeedSynchJob', 'init'), 10, 1);
	}
	public static function getSchedulesCount(){
		$crons = _get_cron_array();
		$result = 0;
		foreach ($crons as $timestamp=>$hooks) { 
			foreach ((array)$hooks as $hook=>$params) {
				if(strpos($hook, self::HOOK)!== false){
					++$result;
				}
			}
		}
		return $result;
	}
	public static function cancelAllSchedules(){
		$crons = _get_cron_array();
		foreach ($crons as $timestamp=>$hooks) { 
			foreach ((array)$hooks as $hook=>$params) {
				if(strpos($hook, self::HOOK)!== false){
					wp_clear_scheduled_hook($hook);
				}
			}
		}
	}
	public static function schedulePending(){
		$result = false;
		$crons = _get_cron_array();
		foreach ($crons as $timestamp=>$hooks) { 
			foreach ((array)$hooks as $hook=>$params) {
				if(strpos($hook, self::HOOK) !== false){
					$result = true;
					break 2;
				}
			}
		}
		return $result;
	}
}
?>