<?php

class XenPushover_DataWriter_AdminAlerts extends XenForo_DataWriter
{
	protected $_priorityId = array(
		-1 => 'low',
		0 => 'normal',
		1 => 'high',
		2 => 'emergency'
	);

	/**
	 * Gets the fields that are defined for the table. See parent for explanation.
	 *
	 * @return array
	 */
	protected function _getFields()
	{
		return array(
			'xenpushover_alert_admin' => array(
				'alert_type'			=> array('type' => self::TYPE_STRING, 'required' => true),
				'enabled'				=> array('type' => self::TYPE_BOOLEAN, 'default' => 1),
				'priority'				=> array('type' => self::TYPE_STRING, 'default' => 'normal',
					'allowedValues' => array('low', 'normal', 'high', 'emergency')
				),
				'sound'					=> array('type' => self::TYPE_STRING, 'default' => ''),
				'last_sent'				=> array('type' => self::TYPE_UINT, 'default' => XenForo_Application::$time),
				'emergency_receipt'		=> array('type' => self::TYPE_STRING, 'default' => '')
			)
		);
	}

	/**
	 * Gets the actual existing data out of data that was passed in. See parent for explanation.
	 *
	 * @param mixed
	 *
	 * @return array|bool
	 */
	protected function _getExistingData($data)
	{
		if (!$id = $this->_getExistingPrimaryKey($data, 'alert_type'))
		{
			return false;
		}

		return array('xenpushover_alert_admin' => $this->_getPushoverModel()->getAdminAlertType($id));
	}

	/**
	 * Gets SQL condition to update the existing record.
	 *
	 * @return string
	 */
	protected function _getUpdateCondition($tableName)
	{
		return 'alert_type = ' . $this->_db->quote($this->getExisting('alert_type'));
	}

	protected function _preSave()
	{
		if ($this->get('enabled') === 0)
		{
			$this->set('sound', '');
			$this->set('last_sent', 0);
			$this->set('emergency_receipt', '');
		}
	}

	/**
	 * @return XenPushover_Model_Pushover
	 */
	protected function _getPushoverModel()
	{
		return $this->getModelFromCache('XenPushover_Model_Pushover');
	}
}