<?php

class XenPushover_DataWriter_AlertTypes extends XenForo_DataWriter
{
	/**
	 * Constant for extra data that holds the value for the phrase
	 * that is the friendly name of this alert type.
	 *
	 * This value is required on inserts.
	 *
	 * @var string
	 */
	const DATA_FRIENDLY_NAME = 'friendlyName';

	const DATA_CONTENT_TYPE_ONLY = 'contentTypeOnly';

	/**
	 * Gets the fields that are defined for the table. See parent for explanation.
	 *
	 * @return array
	 */
	protected function _getFields()
	{
		return array(
			'xenpushover_alert_types' => array(
				'content_type'		=> array('type' => self::TYPE_STRING, 'required' => true),
				'action'			=> array('type' => self::TYPE_STRING, 'required' => true),
				'enabled'			=> array('type' => self::TYPE_BOOLEAN, 'default' => 1)
			)
		);
	}

	/**
	 * 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 (!is_array($data))
		{
			return false;
		}
		else if (isset($data['content_type'], $data['action']))
		{
			$contentType = $data['content_type'];
			$action = $data['action'];
		}
		else if (isset($data[0], $data[1]))
		{
			$contentType = $data[0];
			$action = $data[1];
		}
		else
		{
			return false;
		}

		return array('xenpushover_alert_types' => $this->_getPushoverModel()->getAlertType($contentType, $action));
	}

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

	protected function _postSave()
	{
		$friendlyNamePhrase = $this->getExtraData(self::DATA_FRIENDLY_NAME);
		if ($friendlyNamePhrase !== null)
		{
			$this->_insertOrUpdateMasterPhrase(
				$this->_getFriendlyNamePhraseName($this->get('content_type'), $this->get('action')), $friendlyNamePhrase,
				'', array('global_cache' => 1)
			);
		}
	}

	public function setContentTypePhrase($contentType)
	{
		$friendlyNamePhrase = $this->getExtraData(self::DATA_FRIENDLY_NAME);
		if ($friendlyNamePhrase !== null)
		{
			$this->_insertOrUpdateMasterPhrase(
				$this->_getFriendlyNamePhraseName($contentType), $friendlyNamePhrase,
				'', array('global_cache' => 1)
			);

			$this->getModelFromCache('XenForo_Model_Language')->rebuildLanguageCaches();
		}
	}

	/**
	 * Gets the name of the title phrase for this field.
	 *
	 * @param string $id
	 *
	 * @return string
	 */
	protected function _getFriendlyNamePhraseName($contentType, $action = '')
	{
		return $this->_getPushoverModel()->getFriendlyNamePhraseName($contentType, $action);
	}

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