<?php

class Brivium_Credits_DataWriter_Action extends XenForo_DataWriter
{
	const DATA_ADDON_ID = 'addOnId';
	/**
	 * Constant for extra data that holds the value for the phrase
	 * that is the title of this link.
	 *
	 * This value is required on inserts.
	 *
	 * @var string
	 */
	const DATA_TITLE = 'phraseTitle';
	const DATA_REVERTED_TITLE = 'phraseRevertedTitle';

	/**
	 * Constant for extra data that holds the value for the phrase
	 * that is the explantion of this action.
	 *
	 * @var string
	 */
	const DATA_EXPLAIN = 'phraseExplain';

	/**
	 * Action that represents whether the action cache will be automatically
	 * rebuilt. Defaults to true.
	 *
	 * @var string
	 */
	const OPTION_REBUILD_CACHE = 'rebuildCache';

	/**
	 * Title of the phrase that will be created when a call to set the
	 * existing data fails (when the data doesn't exist).
	 *
	 * @var string
	 */
	protected $_existingDataErrorPhrase = 'BRC_requested_action_not_found';

	/**
	* Gets the fields that are defined for the table. See parent for explanation.
	*
	* @return array
	*/
	protected function _getFields()
	{
		return array(
			'xf_credits_action' => array(
				'action_id'        	=> array('type' => self::TYPE_STRING, 'maxLength' => 100, 'required' => true,
						'verification' => array('$this', '_verifyActionId'), 'requiredError' => 'please_enter_valid_action_id'
				),
				'display_order'     => array('type' => self::TYPE_UINT,   	'default' => 1),
				'global'       		=> array('type' => self::TYPE_BOOLEAN, 'default' => 0),
				'revert'       		=> array('type' => self::TYPE_BOOLEAN, 'default' => 0),
				'link_format'    	=> array('type' => self::TYPE_STRING, 	'default' => ''),
				'addon_id'    		=> array('type' => self::TYPE_STRING, 	'maxLength' => 25,    'default' => ''),
				'template'    		=> array('type' => self::TYPE_STRING, 'default' => ''),
				'multiple_event'    => array('type' => self::TYPE_BOOLEAN, 'default' => 0),
				'allow_negative'    => array('type' => self::TYPE_BOOLEAN, 'default' => 0),
				'negative_handle'    => 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|false
	*/
	protected function _getExistingData($data)
	{
		if (!$id = $this->_getExistingPrimaryKey($data, 'action_id'))
		{
			return false;
		}
		return array('xf_credits_action' => $this->_getActionModel()->getActionById($id));
	}

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

	/**
	 * Gets the default actions for this data writer.
	 */
	protected function _getDefaultActions()
	{
		return array(
			self::OPTION_REBUILD_CACHE => true,
		);
	}

	/**
	 * Verifies that the action ID contains valid characters and does not already exist.
	 *
	 * @param $actionId
	 *
	 * @return boolean
	 */
	protected function _verifyActionId(&$actionId)
	{
		if (preg_match('/[^a-zA-Z0-9_]/', $actionId))
		{
			$this->error(new XenForo_Phrase('please_enter_an_id_using_only_alphanumeric'), 'action_id');
			
			return false;
		}
		if ($actionId !== $this->getExisting('action_id'))
		{
			if ($this->_getActionModel()->getActionById($actionId))
			{
				$this->error(new XenForo_Phrase('BRC_action_ids_must_be_unique'), 'action_id');
				return false;
			}
		}

		return true;
	}
	
	/**
	 * Pre-save handling.
	 */
	protected function _preSave()
	{
		$titlePhrase = $this->getExtraData(self::DATA_TITLE);
		if ($titlePhrase !== null && strlen($titlePhrase) == 0)
		{
			$this->error(new XenForo_Phrase('please_enter_valid_title'), 'title');
		}
	}

	/**
	 * Post-save handling.
	 */
	protected function _postSave()
	{
		$this->_getActionModel()->rebuildActionCache();
		$this->getModelFromCache('Brivium_Credits_Model_Event')->rebuildEventCache();
		if ($this->isUpdate() && $this->isChanged('action_id'))
		{
			$this->_db->update('xf_credits_event',
				array('action_id' => $this->get('action_id')),
				'action_id = ' . $this->_db->quote($this->getExisting('action_id'))
			);
			$this->_db->update('xf_credits_transaction',
				array('action_id' => $this->get('action_id')),
				'action_id = ' . $this->_db->quote($this->getExisting('action_id'))
			);
		}
	}

	/**
	 * update phrase template
	 */
	public function updateContent()
	{
		$addOnId = $this->getExtraData(self::DATA_ADDON_ID)?$this->getExtraData(self::DATA_ADDON_ID):$this->get('addon_id');
		if(!$addOnId)$addOnId = 'Brivium_Credits';
		$titlePhrase = $this->getExtraData(self::DATA_TITLE);
		
		if ($titlePhrase !== null)
		{
			$this->_insertOrUpdateMasterPhrase(
				$this->_getTitlePhraseName($this->get('action_id')), $titlePhrase, $addOnId, array('global_cache'=>true)
			);
		}

		$revertedTitlePhrase = $this->getExtraData(self::DATA_REVERTED_TITLE);
		if ($revertedTitlePhrase !== null)
		{
			$this->_insertOrUpdateMasterPhrase(
				$this->_getRevertedTitlePhraseName($this->get('action_id')), $revertedTitlePhrase, $addOnId, array('global_cache'=>true)
			);
		}

		$explainPhrase = $this->getExtraData(self::DATA_EXPLAIN);
		if ($explainPhrase !== null)
		{
			$this->_insertOrUpdateMasterPhrase(
				$this->_getExplainPhraseName($this->get('action_id')), $explainPhrase, $addOnId, array('global_cache'=>true)
			);
		}
		if($this->isInsert()){
			$data = array(
				'title' => $this->_getActionAlertTemplateName($this->get('action_id')),
				'template' => '<xen:include template="BRC_alert_creditDefault" />',
				'style_id' => 0,
				'addon_id' => $addOnId
			);
			$template = $this->_getTemplateModel()->getTemplateInStyleByTitle($data['title']);
			if(!$template){
				$writer = XenForo_DataWriter::create('XenForo_DataWriter_Template');
				$writer->bulkSet($data);
				$writer->save();
			}
		}else if($this->isUpdate() && $this->isChanged('action_id')){
			$data = array(
				'title' => $this->_getActionAlertTemplateName($this->get('action_id')),
				'template' => '<xen:include template="BRC_alert_creditDefault" />',
				'style_id' => 0,
				'addon_id' => $addOnId
			);
			$template = $this->_getTemplateModel()->getTemplateInStyleByTitle($this->getExisting('action_id'));
			if($template){
				$writer = XenForo_DataWriter::create('XenForo_DataWriter_Template');
				if ($template['template_id'])
				{
					$writer->setExistingData($template['template_id']);
				}
				$writer->bulkSet($data);
				$writer->save();
			}else{
				$template = $this->_getTemplateModel()->getTemplateInStyleByTitle($data['title']);
				if(!$template){
					$writer = XenForo_DataWriter::create('XenForo_DataWriter_Template');
					$writer->bulkSet($data);
					$writer->save();
				}
			}
		}
		
	}
	/**
	 * Post-delete handling.
	 */
	protected function _postDelete()
	{
		$this->_getActionModel()->rebuildActionCache();
		
		$this->_deleteMasterPhrase($this->_getTitlePhraseName($this->get('action_id')));
		$this->_deleteMasterPhrase($this->_getRevertedTitlePhraseName($this->get('action_id')));
		$this->_deleteMasterPhrase($this->_getExplainPhraseName($this->get('action_id')));
		
		$this->_db->delete('xf_credits_event', 'action_id = ' . $this->_db->quote($this->getExisting('action_id')));
		$this->_db->delete('xf_credits_transaction', 'action_id = ' . $this->_db->quote($this->getExisting('action_id')));
		$this->getModelFromCache('Brivium_Credits_Model_Event')->rebuildEventCache();
	}


	/**
	 * Gets the alert template name for a action.
	 *
	 * @param string $actionId
	 *
	 * @return string
	 */
	protected function _getActionAlertTemplateName($actionId)
	{
		return $this->_getActionModel()->getActionAlertTemplateName($actionId);
	}
	/**
	 * Gets the name of the title phrase for this action.
	 *
	 * @param string $actionId
	 *
	 * @return string
	 */
	protected function _getTitlePhraseName($actionId)
	{
		return $this->_getActionModel()->getActionTitlePhraseName($actionId);
	}
	/**
	 * Gets the name of the reverted title phrase for this action.
	 *
	 * @param string $actionId
	 *
	 * @return string
	 */
	protected function _getRevertedTitlePhraseName($actionId)
	{
		return $this->_getActionModel()->getActionRevertedTitlePhraseName($actionId);
	}

	/**
	 * Gets the name of the explain phrase for this action.
	 *
	 * @param string $actionId
	 *
	 * @return string
	 */
	protected function _getExplainPhraseName($actionId)
	{
		return $this->_getActionModel()->getActionExplainPhraseName($actionId);
	}

	/**
	 * Load action model from cache.
	 *
	 * @return Brivium_Credits_Model_Action
	 */
	protected function _getActionModel()
	{
		return $this->getModelFromCache('Brivium_Credits_Model_Action');
	}
	/**
	 * Lazy load the template model object.
	 *
	 * @return  XenForo_Model_Template
	 */
	protected function _getTemplateModel()
	{
		return $this->getModelFromCache('XenForo_Model_Template');
	}

}