#!/opt/local/bin/php
<?php

chdir('..');
require_once 'common.php';
define('VKTIMEOUT', 1);


$db = Db::getInstance();
$vk = new Vkontakte();

$continue = true;
while ($continue) {
	$queue = $db->getRows($db->q("SELECT * FROM beathaven.queue WHERE status=0 OR status=2 ORDER BY priority DESC, status ASC, times_failed ASC LIMIT 100"));
	if (!$queue || count($queue) == 0) {
		$continue = false;
	} else {
		foreach ($queue as $t) {
			echo "#{$t['track_id']} {$t['track_title']}\n";
			echo "Loading file list: ";
			$t1 = microtime(true);
			$vk->parse($t['track_title']);
			$vk->parseHtml();
			$files = $vk->getFiles();
			if ($files && count($files) > 0) {
				echo "OK (".count($files).")\n";
				$tmp = explode(' - ', $t['track_title']); $artist_name = $tmp[0]; unset($tmp[0]); $track_name = implode(' - ', $tmp);
				$files = VkontakteMP3::check($files, $artist_name, $track_name, $t['track_length']);
				BeatDB::set($t['track_id'], $files);
				echo "Good files: ". count($files) ."\n\n";
				$db->q("UPDATE beathaven.queue SET status=1 WHERE track_id=". $t['track_id']);
				@unlink('/www/parser_data/html/'. $t['track_id'] .'.html');
			} else {
				file_put_contents('/www/parser_data/html/'. $t['track_id'] .'.html', $vk->getHtml());
				echo "FAILED\n\n";
				$db->q("UPDATE beathaven.queue SET status = 2, times_failed = times_failed + 1 WHERE track_id=". $t['track_id']);
			}
			$t2 = microtime(true);
			if ($t2 - $t1 < VKTIMEOUT) {
				sleep(ceil(VKTIMEOUT - ($t2 - $t1)));
			}
		}
		sleep(5);
	}
}
