<?php

class SpiderController {

	public static function spider_pdfs() {
		return blade("spider_pdfs");
	}

	public static function spider_pages() {
		return blade("spider_pages");
	}
	
	public static function api_pdfs() {
		$pdfs = Spider::find([["status", "=", "N"]])->orderBy("id")->limit(20)->all();

		return $pdfs;
	}

	public static function api_pages() {
		$pages = SpiderPage::find([["status", "=", "O"], ["title", "!=", ""]])->orderBy("title")->limit(20)->all();

		return $pages;
	}

	public static function api_reject_pdf($id = null) {
		if ($id == null) return [];

		$i = explode(",", $id);
		foreach ($i as $id) {
			$pdf = new Spider($id);
			if ($pdf) {
				$pdf->status = "B";
				$pdf->save();
			}
		}
		return SpiderController::api_pdfs();
	}

	public static function api_accept_pdf($_request, $id = null) {
		if ($id == null) return [];

		$i = explode(",", $id);
		foreach ($i as $id) {
			$pdf = new Spider($id);
			if ($pdf) {
				$pdf->status = "D";
				$pdf->save();

				$job = new DownloadJob;

				$job->queued = time();
				$job->started = 0;
				$job->finished = 0;
				$job->processed = 0;
				$job->url = $pdf->url;
				$job->owner = get_user()->id;
				$job->file = sprintf("download/file-%08X-%08X", rand(), time());

				$job->save();
			}
		}
		return SpiderController::api_pdfs();
	}

	public static function api_reject_page($_request, $id) {
		$i = explode(",", $id);
		foreach ($i as $id) {
			$page = new SpiderPage($id);
			if ($page) {
				$page->status = "B";
				$page->save();
			}
		}
		return SpiderController::api_pages();
	}

	public static function api_accept_page($id) {

		$i = explode(",", $id);
		foreach ($i as $id) {
			$page = new SpiderPage($id);
			if ($page) {
				$page->status = "N";
				$page->save();
			}
		}
		return SpiderController::api_pages();
	}
}

	

