<?php

class XenPushover_Deferred_Pushover extends XenForo_Deferred_Abstract
{
	protected $_pushoverModel = null;

	protected $_db = null;

	public function execute(array $deferred, array $data, $targetRunTime, &$status)
	{
		$pushoverModel = $this->_getPushoverModel();
		$db = $this->_getDb();

		foreach ($pushoverModel->getQueue() AS $alert)
		{
			if ($alert['queue_date'] <= XenForo_Application::$time)
			{
				if (!$pushoverModel->push($alert['alert_id'], $alert['user_id']))
				{
					$pushoverModel->queue($alert['alert_id'], $alert['user_id'], XenForo_Application::$time + (5 * 60));
				}
				else
				{
					$db->delete('xenpushover_alert_queue', 'queue_id = ' . $db->quote($alert['queue_id']));
				}
			}
		}

		if ($runTime = $pushoverModel->getNextRunTime())
		{
			XenForo_Application::defer('XenPushover_Deferred_Pushover', array(), 'XenPushoverQueue', false, $runTime);
		}

		return false;
	}

	/**
	 * @return XenPushover_Model_Pushover
	 */
	protected function _getPushoverModel()
	{
		if (!$this->_pushoverModel)
		{
			$this->_pushoverModel = XenForo_Model::create('XenPushover_Model_Pushover');
		}

		return $this->_pushoverModel;
	}

	/**
	 * @return Zend_Db_Adapter_Abstract
	 */
	protected function _getDb()
	{
		if (!$this->_db)
		{
			$this->_db = XenForo_Application::getDb();
		}

		return $this->_db;
	}
}