<?php

class XenPushover_Install
{
	protected static $_db = null;

	protected static function _canBeInstalled(&$error)
	{
		if (XenForo_Application::$versionId < 1030070)
		{
			$error = 'This add-on requires XenForo 1.3.0 or higher.';
			return false;
		}

		return true;
	}

	public static function installer($addOn)
	{
		if (!self::_canBeInstalled($error))
		{
			throw new XenForo_Exception($error, true);
		}

		self::stepTables();
		self::stepData();
	}

	public static function uninstaller()
	{
		self::stepDeleteTables();
	}

	public static function stepTables()
	{
		$db = self::_getDb();

		foreach (self::_getTables() AS $tableSql)
		{
			try
			{
				$db->query($tableSql);
			}
			catch (Zend_Db_Exception $e) {}
		}
	}

	public static function stepDeleteTables()
	{
		$db = self::_getDb();

		foreach (self::_getTables() AS $tableName => $tableSql)
		{
			try
			{
				$db->query("DROP TABLE IF EXISTS $tableName");
			}
			catch (Zend_Db_Exception $e) {}
		}
	}

	protected  static function _getTables()
	{
		$tables = array();

		$tables['xenpushover_alert_types'] = "
			CREATE TABLE IF NOT EXISTS xenpushover_alert_types (
				content_type VARBINARY(25) NOT NULL,
				action VARBINARY(25) NOT NULL,
				enabled TINYINT UNSIGNED NOT NULL DEFAULT 1,
			PRIMARY KEY (content_type, action)
			) ENGINE=InnoDB DEFAULT CHARSET=utf8
		";

		$tables['xenpushover_alert_admin'] = "
			CREATE TABLE xenpushover_alert_admin (
				alert_type ENUM('', 'server_error', 'user_approval') NOT NULL DEFAULT 'server_error',
				enabled TINYINT(3) UNSIGNED NOT NULL DEFAULT 1,
				priority ENUM('low','normal','high','emergency') NOT NULL DEFAULT 'normal',
				sound VARCHAR(30) NOT NULL DEFAULT '',
				last_sent INT(10) UNSIGNED NOT NULL DEFAULT 0,
				emergency_receipt VARCHAR(30) NOT NULL DEFAULT '',
			PRIMARY KEY (alert_type)
			) ENGINE=InnoDB DEFAULT CHARSET=utf8
		";

		$tables['xenpushover_alert_optout'] = "
			CREATE TABLE IF NOT EXISTS xenpushover_alert_optout (
				user_id INT(10) UNSIGNED NOT NULL,
				alert VARBINARY(50) NOT NULL,
			PRIMARY KEY (user_id, alert)
			) ENGINE=InnoDB DEFAULT CHARSET=utf8
		";

		$tables['xenpushover_alert_priority'] = "
			CREATE TABLE IF NOT EXISTS xenpushover_alert_priority (
				user_id INT(10) UNSIGNED NOT NULL,
				alert VARBINARY(50) NOT NULL,
				priority TINYINT NOT NULL DEFAULT 0,
			PRIMARY KEY (user_id, alert)
			) ENGINE=InnoDB DEFAULT CHARSET=utf8
		";

		$tables['xenpushover_alert_queue'] = "
			CREATE TABLE IF NOT EXISTS xenpushover_alert_queue (
				queue_id INT(10) UNSIGNED AUTO_INCREMENT,
				alert_id INT(10) UNSIGNED NOT NULL,
				user_id INT(10) UNSIGNED NOT NULL,
				queue_date INT(10) UNSIGNED NOT NULL DEFAULT 0,
			PRIMARY KEY (queue_id)
			) ENGINE=InnoDB DEFAULT CHARSET=utf8
		";

		return $tables;
	}

	public static function stepData()
	{
		$db = self::_getDb();

		foreach (self::_getAlertData() AS $alertData)
		{
			try
			{
				$db->insert('xenpushover_alert_types', $alertData);
			}
			catch (Zend_Db_Exception $e) {}
		}

		foreach (self::_getAdminAlertData() AS $adminAlertData)
		{
			$db->query($adminAlertData);

			try
			{

			}
			catch (Zend_Db_Exception $e) {}
		}
	}

	protected static function _getAlertData()
	{
		/** @var $alertModel XenForo_Model_Alert */
		$alertModel = XenForo_Model::create('XenForo_Model_Alert');

		$alertHandlers = $alertModel->getContentTypesWithField('alert_handler_class');

		$alertTypes = array();
		$regExpClause = '';
		foreach ($alertHandlers AS $contentType => $class)
		{
			if ($contentType == 'conversation')
			{
				continue;
			}

			$templatePrefix = 'alert_' . $contentType . '_';

			$alertTypes[$contentType]['templatePrefix'] = $templatePrefix;
			$regExpClause .= $templatePrefix . '|';
		}

		$db = self::_getDb();

		$templates = $db->fetchPairs('
			SELECT title, title
			FROM xf_template
			WHERE title REGEXP ' . $db->quote(rtrim($regExpClause, '|')) . '
		');

		$data = array();

		foreach ($alertTypes AS $contentType => &$alertType)
		{
			foreach ($templates AS $template)
			{
				if (strstr($template, $alertType['templatePrefix']))
				{
					$action = str_replace($alertType['templatePrefix'], '', $template);
					$data[] = array(
						'content_type' => $contentType,
						'action' => $action,
						'enabled' => 1
					);
				}
			}
		}

		return $data;
	}
	
	protected static function _getAdminAlertData()
	{
		$data = array();
		
		$data[] = "
			INSERT IGNORE INTO xenpushover_alert_admin
				(alert_type, enabled, priority, sound, last_sent, emergency_receipt)
			VALUES
				('server_error', 1, 'normal', '', 0, ''),
				('user_approval', 1, 'normal', '', 0, '')
		";
		
		return $data;
	}

	/**
	 * @return Zend_Db_Adapter_Abstract
	 */
	protected static function _getDb()
	{
		if (!self::$_db)
		{
			self::$_db = XenForo_Application::getDb();
		}

		return self::$_db;
	}
}