<?php

class XenPushover_CronEntry_Scrape
{
	public static function scrapeForAlerts()
	{
		/** @var $pushoverModel XenPushover_Model_Pushover */
		$pushoverModel = XenForo_Model::create('XenPushover_Model_Pushover');

		$users = $pushoverModel->getScrapeUsers();
		foreach ($users AS $userId => $user)
		{
			$user['permissions'] = XenForo_Permission::unserializePermissions($user['global_permission_cache']);

			if ($general = $user['permissions']['general'])
			{
				if ($general['associateXenPushover'] === true)
				{
					$extraData = @unserialize($user['extra_data']);
					if (!$extraData || empty($extraData['url']))
					{
						continue;
					}

					$url = rtrim($extraData['url'], '/');
					if (strpos($url, 'index.php'))
					{
						$url .= '?';
						$queryStringPrefix = '&';
					}
					else
					{
						$url .= '/';
						$queryStringPrefix = '?';
					}
					$loginUrl = $url . 'login/login';

					$client = XenForo_Helper_Http::getClient($loginUrl);
					$client->setParameterPost(array(
						'login' => $extraData['username'],
						'password' => $extraData['password']
					));
					$client->setCookieJar();
					$client->setHeaders('X-Requested-With', 'XMLHttpRequest');

					try
					{
						$request = $client->request(Zend_Http_Client::POST);
					}
					catch (Exception $e)
					{
						// This should retry next time around.
						continue;
					}

					$result = $request->getBody();

					$dom = new Zend_Dom_Query($result);

					$LoggedIn = $dom->query('html.LoggedIn');
					if ($LoggedIn->count() === 0)
					{
						continue;
					}

					$alertsUrl = $url . 'account/alerts' . $queryStringPrefix . 'skip_mark_read=1';

					$client->setUri($alertsUrl);
					$client->setHeaders('X-Requested-With', 'XMLHttpRequest');

					try
					{
						$request = $client->request(Zend_Http_Client::GET);
					}
					catch (Exception $e) { continue; }

					$result = $request->getBody();

					$dom = new Zend_Dom_Query($result);

					$alertsList = $dom->query('ol.alerts ol');
					$alertItems = $alertsList->current()->getElementsByTagName('li');

					$alerts = array();
					foreach ($alertItems AS $alertItem)
					{
						$id = str_replace('alert', '', $alertItem->getAttribute('id'));
						$alerts[intval($id)] = $alertsList->current()->ownerDocument->saveXML($alertItem);
					}
					krsort($alerts, SORT_NUMERIC);

					reset($extraData['alerts']);
					reset($alerts);

					$alertsSent = array();
					foreach ($alerts AS $alertId => $alert)
					{
						if ($alertId <= key($extraData['alerts']))
						{
							continue;
						}

						$alertsSent[$alertId] = $alert;
					}

					foreach ($alertsSent AS $alertId => $alert)
					{
						$pushoverModel->pushScrapedAlert($alert, $alertId, $extraData);
					}

					$extraData['alerts'] = $alerts;
					XenForo_Model::create('XenForo_Model_UserExternal')->updateExternalAuthAssociation(
						'xenpushoverScrape', $user['provider_key'], $userId, $extraData
					);
				}
			}
		}

		return true;
	}
}