<?php

class ModEss_Listener_Cog
{

	// controller call
	public static function preDispatch(XenForo_Controller $controller, $action)
	{
		if ($controller instanceof XenForo_ControllerPublic_Abstract)
		{
			self::_updateModLogSessionCounts();
		}
	}

	// set data registry
	public static function initDependencies(XenForo_Dependencies_Abstract $dependencies, array $data)
	{
		if ($dependencies instanceof XenForo_Dependencies_Public)
		{
			$dataRegistryModel = XenForo_Model::create('XenForo_Model_DataRegistry');
			$modLogCounts = $dataRegistryModel->get('modLogCounts');

			if (!is_array($modLogCounts))
			{
				$modLogCounts = XenForo_Model::create('ModEss_Model_ModEss')->rebuildSessionModLogCountsCache();
			}

			if (!empty($modLogCounts))
			{
				XenForo_Application::set('modLogCounts', $modLogCounts);
			}
		}
	}

	// controller class extensions
	public static function loadModeratorLogHandlerThread($class, array &$extend)
	{
		if ($class == 'XenForo_ModeratorLogHandler_Thread')
		{
			$extend[] = 'ModEss_ModeratorLogHandler_Thread';
		}
	}

	// class extensions
	public static function loadClassLogHandlerResource($class, array &$extend)
	{
		if ($class == 'XenResource_ModeratorLogHandler_Resource')
		{
			$extend[] = 'ModEss_XenResource_ModeratorLogHandler_Resource';
		}
	}

	// class extensions
	public static function loadClassLogHandlerResourceUpdate($class, array &$extend)
	{
		if ($class == 'XenResource_ModeratorLogHandler_Update')
		{
			$extend[] = 'ModEss_XenResource_ModeratorLogHandler_Update';
		}
	}

	// controller class extensions
	public static function loadClassController($class, array &$extend)
	{
		if ($class == 'XenForo_ControllerPublic_Thread')
		{
			$extend[] = 'ModEss_ControllerPublic_Thread';
		}
		else if ($class == 'XenForo_ControllerPublic_InlineMod_Thread')
		{
			$extend[] = 'ModEss_XenForo_ControllerPublic_InlineMod_Thread';
		}
		else if ($class == 'XenForo_ControllerPublic_InlineMod_Post')
		{
			$extend[] = 'ModEss_XenForo_ControllerPublic_InlineMod_Post';
		}
		else if ($class == 'XenForo_ControllerPublic_Forum')
		{
			$extend[] = 'ModEss_ControllerPublic_Forum';
		}
		else if ($class == 'XenForo_ControllerPublic_Account')
		{
			$extend[] = 'ModEss_ControllerPublic_Account';
		}
		else if ($class == 'XenForo_ControllerPublic_Member')
		{
			$extend[] = 'ModEss_ControllerPublic_Member';
		}
	}

	// model calss extensions
	public static function loadClassModel($class, array &$extend)
	{
		$validClasses = array(
			'XenForo_Model_ModerationQueue',
			'XenForo_Model_InlineMod_Post'
		);
		if (in_array($class, $validClasses))
		{
			$extend[] = 'ModEss_' . $class;
		}

		if ($class == 'XenForo_Model_Post')
		{
			$extend[] = 'ModEss_Model_Post';
		}
		else if ($class == 'XenForo_Model_Thread')
		{
			$extend[] = 'ModEss_Model_Thread';
		}
		else if ($class == 'XenForo_Model_Log')
		{
			$extend[] = 'ModEss_Model_Log';
		}
		else if ($class == 'XenForo_Model_Node')
		{
			$extend[] = 'ModEss_Model_Node';
		}
		else if ($class == 'XenForo_Model_Permission')
		{
			$extend[] = 'ModEss_Model_Permission';
		}
		else if ($class == 'XenForo_Model_Moderator')
		{
			$extend[] = 'ModEss_Model_Moderator';
		}
		else if ($class == 'XenForo_Model_EditHistory')
		{
			$extend[] = 'ModEss_Model_EditHistory';
		}
	}

	// view class extensions
	public static function loadClassView($class, array &$extend)
	{
		if ($class == 'XenForo_ViewPublic_ModerationQueue_List')
		{
			$extend[] = 'ModEss_ViewPublic_ModerationQueue_List';
		}
		else if ($class == 'XenForo_ViewPublic_Forum_View')
		{
			$extend[] = 'ModEss_ViewPublic_Forum_View';
		}
		else if ($class == 'XenForo_ViewPublic_Account_Preferences')
		{
			$extend[] = 'ModEss_ViewPublic_Account_Preferences';
		}
	}

	// datawriter class extensions
	public static function loadClassDataWriter($class, array &$extend)
	{
		if ($class == 'XenForo_DataWriter_User')
		{
			$extend[] = 'ModEss_DataWriter_User';
		}
		else if ($class == 'XenForo_DataWriter_ModeratorLog')
		{
			$extend[] = 'ModEss_DataWriter_ModeratorLog';
		}
		else if ($class == 'XenForo_DataWriter_Discussion_Thread')
		{
			if (XenForo_Application::get('options')->modess_sticky_thread_order)
			{
				$extend[] = 'ModEss_DataWriter_Discussion_Thread';
			}
		}
		else if ($class == 'XenForo_DataWriter_Warning')
		{
			if (XenForo_Application::get('options')->modess_log_warnings['dolog'])
			{
				$extend[] = 'ModEss_DataWriter_Warning';
			}
		}
		else if ($class == 'XenForo_DataWriter_ConversationMaster')
		{
			$extend[] = 'ModEss_XenForo_DataWriter_ConversationMaster';
		}
	}

	// preload the templates
	public static function templateCreate($templateName, array &$params, XenForo_Template_Abstract $template)
	{
		if ($templateName == 'PAGE_CONTAINER')
		{
			$template->preloadTemplate('modess_moderator_bar_mod_log_counts');
		}
	}

	// template hooks
	public static function templateHook($hookName, &$contents, array $hookParams, XenForo_Template_Abstract $template)
	{
		if ($hookName == 'moderator_bar')
		{
			self::_addModeratorBarSessionLog($contents, $hookParams, $template);
		}
		else if ($hookName == 'account_preferences_options')
		{
			self::_addModLogPreferences($contents, $hookParams, $template);
		}
	}

	// thread view dispatch
	public static function threadViewPostDispatch($controller, $response, $controllerName, $action)
	{
		if (!($response instanceof XenForo_ControllerResponse_View))
		{
			return;
		}

		if ($response->viewName != 'XenForo_ViewPublic_Thread_View' || empty($response->params['thread']) || empty($response->params['posts']))
		{
			return;
		}

		if (!empty($response->params['thread']))
		{
			$response->params['thread']['canUseNotes'] = (XenForo_Visitor::getInstance()
					->hasPermission('general', 'canModeratorDiscussion') || XenForo_Visitor::getInstance()
					->hasNodePermission($response->params['thread']['node_id'], 'canModeratorDiscussion'));
		}

		$thread = $response->params['thread'];
		if ($thread['discussion_type'] != 'modess_action_discussion')
		{
			return;
		}

		$posts = $response->params['posts'];

        if (empty($posts[$thread['first_post_id']])) {
            $post = XenForo_Model::create('XenForo_Model_Post')->getPostById($thread['first_post_id']);
        }
        else {
            $post = $posts[$thread['first_post_id']];
        }

		$logId = $post['message'];
		$modLogModel = XenForo_Model::create('XenForo_Model_Log');
		///////////////////////////////////////////////////////////////////////////////////////
		//this part for the thread discussion for every moderator/////////////////////////////////////////////////
		$moderator_discussion = explode('_', $logId);
		if (is_array($moderator_discussion) and isset($moderator_discussion[1]))
		{

			$discussion_id = $moderator_discussion[1];
			$entry[$discussion_id] = XenForo_Model::create('ModEss_Model_ModeratorDiscussion')
				->getModEntryById($discussion_id);

			if (!$entry[$discussion_id])
			{
				return false;
			}
			$forum_id = $entry[$discussion_id]['forum_id'];
			$entry[$discussion_id]['content_type'] = 'thread';
			$entry[$discussion_id]['action'] = 'approve';
			$entry[$discussion_id]['discussion_content_id'] = $discussion_id;
			$entry[$discussion_id]['content_title'] = $entry[$discussion_id]['title'];
			$forum = array(
				"node_id" => "$forum_id",
				"node_title" => "Forum"
			);
			$entry[$discussion_id]['action_params'] = json_encode($forum);
			//genrating link of forum and thread
			$entry = $modLogModel->addLinksToModLogEntries($entry);
			$entry = $entry[$discussion_id];
			$entry['ip_address'] = '';
			$entry['actionText'] = $entry['title'];
			$entry = $modLogModel->prepareModeratorLogEntry($entry);
			//unset first post
			unset($response->params['posts'][$thread['first_post_id']]);
			$response->params['thread']['modess_note_thread'] = 1;
			$discussion_content_id = $entry['discussion_content_id'];
			$response->params['thread']['note_link'] = "index.php?threads/$discussion_content_id";
			$response->params['modess_log_item'] = $entry;
		}
		/////////////////////////////////////////////////////////////////////////////////////////////////
		///////////////////////////////////////////////////////////////////////////////////////////////
		else
		{

			if (!is_numeric($logId) || $logId == 0)
			{
				return;
			}


			$entries = $modLogModel->getModLogEntriesByIds(array($logId));

			if (!$entries)
			{
				return false;
			}

			$entries = $modLogModel->addLinksToModLogEntries($entries); // add content links
			$entries = $modLogModel->prepareModeratorLogEntries($entries); // prepare logs

			$entry = $entries[$logId];
			if (!$entry)
			{
				return;
			}
			$entry = $modLogModel->prepareModeratorLogEntry($entry);
			if (!$entry)
			{
				return;
			}

			unset($response->params['posts'][$thread['first_post_id']]);

			$response->params['modess_log_item'] = $entry;
		}
	}

	// adds the moderator session log to the moderator bar
	protected static function _addModeratorBarSessionLog(&$contents, $hookParams, XenForo_Template_Abstract $template)
	{
		$visitor = XenForo_Visitor::getInstance();
		if ($visitor['is_moderator'] && $visitor->hasPermission('general', 'canViewModLogCounts'))
		{
			$modEssModel = XenForo_Model::create('ModEss_Model_ModEss');
			if ($modEssModel->isModLogCountsActive($visitor['user_id']))
			{
				$hookParams = $template->getParams();
				$maxEntries = XenForo_Application::get('options')->modess_mod_log_max_entries;
				if ($hookParams['session']['modLogCounts']['total'] > $maxEntries)
				{
					$hookParams['maxCountReached'] = true; // limit the display count to the maximum by adding a '+' after displaying as a number (for languages) in template
					$hookParams['session']['modLogCounts']['total'] = $maxEntries;
				}

				$contents .= $template->create('modess_moderator_bar_mod_log_counts', $hookParams);
			}
		}
	}

	// add option to select mod log alert items
	protected static function _addModLogPreferences(&$contents, $hookParams, XenForo_Template_Abstract $template)
	{
		$visitor = XenForo_Visitor::getInstance();

		if ($visitor['is_moderator'] && $visitor->hasPermission('general', 'canViewModLogCounts'))
		{
			$modEssModel = XenForo_Model::create('ModEss_Model_ModEss');
			if ($modEssModel->isModLogCountsActive($visitor['user_id']))
			{
				if ($template->getParam('isOverlay'))
				{
					$contents .= $template->create('modess_account_preferences_options_overlay', $hookParams);
				}
				else
				{
					// if Thread Ban is installed then add those actions
					$addOns = XenForo_Application::get('addOns'); // $this->_getDataRegistryModel()->get('addOns');
					if (isset($addOns['ThreadBan']))
					{
						$doIncludeThreadBans = 1;
					}
					else
					{
						$doIncludeThreadBans = 0;
					}

					// if Resource Manager is installed then add those actions
					if (isset($addOns['XenResource']) && $visitor->hasPermission('resource', 'view'))
					{
						$doIncludeResources = 1;
					}
					else
					{
						$doIncludeResources = 0;
					}

					$doIncludeWarnings = XenForo_Application::get('options')->modess_log_warnings['modlog'] && $visitor->hasPermission('general',
						'viewWarning') ? 1 : 0;

					$actionPreferences = $modEssModel->getModLogActionPreferencesByUserId($visitor['user_id'],
						$doIncludeThreadBans, $doIncludeResources, $doIncludeWarnings);

					$hookParams['doIncludeThreadBans'] = $doIncludeThreadBans;
					$hookParams['doIncludeResources'] = $doIncludeResources;
					$hookParams['doIncludeWarnings'] = $doIncludeWarnings;
					$hookParams['actionPreferences'] = $actionPreferences;
					$contents .= $template->create('modess_account_preferences_options', $hookParams);
				}
			}
		}
	}

	// updates the counts in the session for the session mod log.
	protected static function _updateModLogSessionCounts()
	{
		$visitor = XenForo_Visitor::getInstance();

		if (!$visitor['is_moderator'] || !$visitor->hasPermission('general', 'canViewModLogCounts'))
		{
			return;
		}

		$visitorId = $visitor['user_id'];
		$modEssModel = XenForo_Model::create('ModEss_Model_ModEss');
		if ($logCounts = $modEssModel->getModLogCounts($visitorId))
		{
			if ($logCounts['isActive'])
			{
				$session = XenForo_Application::get('session');
				$sessionLogCounts = $session->get('modLogCounts');

				if (!is_array($sessionLogCounts) || ($sessionLogCounts['total'] <> $logCounts['total']))
				{
					$session->set('modLogCounts', $logCounts);
				}
			}
		}
	}

}
