<?php

/**
* Data writer for Sticky Order.
*
* @package ModEss - Sticky Thread Order
*/
class ModEss_DataWriter_STO extends XenForo_DataWriter
{
	/**
	* Gets the fields that are defined for the table. See parent for explanation.
	*
	* @return array
	*/
	protected function _getFields()
	{
		return array(
				'sticky_thread_order'	=> array(
				'thread_id'   			=> array('type' => self::TYPE_UINT, 'required' => true),
				'display_order' 		=> array('type' => self::TYPE_UINT, 'required' => true, 'verification' => array('$this', '_verifyDisplayOrder'))
			)
		);
	}

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

		return array('sticky_thread_order' => $this->_getSTOModel()->getStickyOrder($threadId));
	}

	/**
	* Gets SQL condition to update the existing record.
	*
	* @return string
	*/
	protected function _getUpdateCondition($tableName)
	{
		return 'thread_id = ' . $this->_db->quote($this->getExisting('thread_id'));
	}
	
	/**
	 * Verifies the display order is smaller than 1000 (as size of input box is 3).
	 *
	 * @param integer $displayOrder
	 *
	 * @return boolean
	 */
	protected function _verifyDisplayOrder(&$displayOrder)
	{
		if ($displayOrder > 999)
		{
			$displayOrder = 999;
		}
		
		return true;
	}

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