<?php

/**
 * Model for Sticky Thread Order functions.
 *
 * @package ModEss - Sticky Thread Order
 */
class ModEss_Model_STO extends XenForo_Model
{
	/**
	 * Fetch the sticky order of a thread
	 *
	 * @param integer $threadId
	 *
	 * @return integer
	 */
	public function getStickyOrder($threadId)
	{
		return $this->_getDb()->fetchRow('
			SELECT *
			FROM sticky_thread_order
			WHERE thread_id = ?
			LIMIT 1', $threadId
		);
	}
	
	/**
	 * Add or Edit a sticky order
	 *
	 * @param integer $stickyOrder
	 * @param integer $threadId
	 */
	public function addOrEditStickyOrder($stickyOrder, $threadId)
	{
		$stickyOrder = intval($stickyOrder);
		$threadId = intval($threadId);
		
		if ($stickyOrder > 0 && $threadId > 0)
		{
			$exists = $this->getStickyOrder($threadId);
			if (empty($exists))
				$existingStickyOrder = 0;
			else
				$existingStickyOrder = $exists['display_order'];
			
			if ($existingStickyOrder != $stickyOrder)
			{
				$dw = XenForo_DataWriter::create('ModEss_DataWriter_STO');
				
				if ($existingStickyOrder)
					$dw->setExistingData($threadId);
				else
					$dw->set('thread_id', $threadId);
					
				$dw->set('display_order', $stickyOrder);
				$dw->save();
			}
		}
	}
	
	/**
	 * Delete a sticky order
	 *
	 * @param integer $threadId
	 */
	public function deleteStickyOrder($threadId)
	{
		$threadId = intval($threadId);
		
		$exists = $this->getStickyOrder($threadId);
		if (!empty($exists))
		{
			$dw = XenForo_DataWriter::create('ModEss_DataWriter_STO');
			$dw->setExistingData($threadId);
			$dw->delete();
		}	
	}
}