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

chdir('..');
require_once 'common.php';
Config::loadFile('app', 'config/app.ini');

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

$continue = true;
while ($continue) {
	$queue = $db->getRows($db->q("SELECT * FROM beathaven.queue WHERE status=2 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']);
			$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']);
			} else {
				echo "FAILED\n\n";
				$db->q("UPDATE beathaven.queue SET status=2 WHERE track_id=". $t['track_id']);
			}
			$t2 = microtime(true);
			if ($t2 - $t1 < 5) {
				sleep(ceil(5 - ($t2 - $t1)));
			}
		}
	}
}
