<?php

class GritterNotifications_Install
{
	protected static $_db = null;

	protected static function _canBeInstalled(&$error)
	{
		if (XenForo_Application::$versionId < 1020070)
		{
			$error = 'This add-on requires XenForo 1.2.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::stepDeleteObsoleteFiles();

		/** For legacy reasons */
		self::addColumnIfNotExists('create_username', 'varchar(50) NOT NULL DEFAULT ""', 'page_criteria');
		self::addColumnIfNotExists('create_date', 'int(10) unsigned NOT NULL DEFAULT 0', 'create_username');
		self::addColumnIfNotExists('edit_username', 'varchar(50) NOT NULL DEFAULT ""', 'create_date');
		self::addColumnIfNotExists('edit_date', 'int(10) unsigned NOT NULL DEFAULT ""', 'edit_username');
	}

	public static function addColumnIfNotExists($fieldName, $fieldDef, $after)
	{
		$db = self::_getDb();

		$exists = $db->fetchRow("
			SHOW COLUMNS
			FROM xf_notification
			WHERE Field = ?
		", $fieldName);

		if (!$exists)
		{
			$db->query("
    			ALTER TABLE xf_notification ADD {$fieldName} {$fieldDef} AFTER {$after}
    		");
		}
	}

	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['xf_notification'] = "
			CREATE TABLE IF NOT EXISTS xf_notification (
				notification_id int(10) unsigned NOT NULL AUTO_INCREMENT,
				name text NOT NULL,
				description varchar(255) DEFAULT NULL,
				active tinyint(3) NOT NULL DEFAULT 1,
				dismissible tinyint(3) NOT NULL DEFAULT 0,
				sticky tinyint(3) NOT NULL DEFAULT 0,
				style enum('gritter-dark','gritter-light','custom','easy') DEFAULT 'gritter-dark',
				custom_style mediumtext,
				custom_easy_bg varchar(25) NOT NULL DEFAULT 'rgba(0, 0, 0, 0.85)',
				custom_easy_text varchar(25) NOT NULL DEFAULT 'rgba(238, 238, 238, 1)',
				title varchar(255) NOT NULL DEFAULT '',
				text mediumtext NOT NULL,
				showimage enum('avatar','0','image') DEFAULT 'avatar',
				image varchar(255) DEFAULT '',
				playsound varchar(255) NOT NULL DEFAULT 0,
				sound varchar(255) DEFAULT '',
				tempclosetime int(10) NOT NULL DEFAULT 0,
				showtime int(10) NOT NULL DEFAULT 6000,
				fadeintime int(10) NOT NULL DEFAULT 100,
				fadeouttime int(10) NOT NULL DEFAULT 100,
				delay int(10) NOT NULL DEFAULT 0,
				user_criteria mediumblob NOT NULL,
				page_criteria mediumblob NOT NULL,
				create_username varchar(50) NOT NULL DEFAULT '',
				create_date int(10) unsigned NOT NULL DEFAULT 0,
				edit_username varchar(50) DEFAULT '',
				edit_date int(10) unsigned DEFAULT 0,
				PRIMARY KEY (notification_id)
			) ENGINE=InnoDB DEFAULT CHARSET=utf8
		";

		$tables['xf_notification_dismissed'] = "
			CREATE TABLE IF NOT EXISTS xf_notification_dismissed (
				notification_id INT(10) UNSIGNED NOT NULL,
				user_id INT(10) UNSIGNED NOT NULL,
				dismiss_date INT(10) UNSIGNED NOT NULL DEFAULT '0',
				PRIMARY KEY (notification_id, user_id),
				KEY user_id (user_id)
			) ENGINE=InnoDB DEFAULT CHARSET=utf8
		";

		return $tables;
	}

	public static function stepDeleteObsoleteFiles()
	{
		self::deleteAll('js/tinymce');
	}

	public static function deleteAll($directory, $empty = false)
	{
		if (substr($directory, -1) == '/')
		{
			$directory = substr($directory, 0, -1);
		}

		if (!file_exists($directory) || !is_dir($directory))
		{
			return false;
		}
		elseif(!is_readable($directory))
		{
			return false;
		}
		else
		{
			$directoryHandle = opendir($directory);

			while ($contents = readdir($directoryHandle))
			{
				if($contents != '.' && $contents != '..')
				{
					$path = $directory . '/' . $contents;

					if(is_dir($path))
					{
						self::deleteAll($path);
					}
					else
					{
						@unlink($path);
					}
				}
			}

			closedir($directoryHandle);

			if ($empty == false)
			{
				if (!@rmdir($directory))
				{
					return false;
				}
			}

			return true;
		}
	}

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

		return self::$_db;
	}
}