<?php

class SystemController {
	public static function status() {
		$status = [
			"B" => "Blacklisted",
			"N" => "Pending",
			"F" => "Failed",
			"D" => "Done",
			"Y" => "Done",
			"W" => "Postponed",
			"P" => "Processing",
			"X" => "Deleted",
			"O" => "Off-site",
			"Q" => "Postponed",
			"R" => "Redirect",
		];

		$q = DB::getInstance()->query("select count(id) as c, status from pages group by status order by status");
		$spider = [];
		while ($r = DB::getInstance()->nextRecord($q)) {
			$spider[@$status[$r->status]] = $r->c;
		}

		$q = DB::getInstance()->query("select count(id) as c, status from spider group by status order by status");
		$pdf = [];
		while ($r = DB::getInstance()->nextRecord($q)) {
			$pdf[@$status[$r->status]] = $r->c;
		}

		$q = DB::getInstance()->query("select count(id) as c, ocr from revision group by ocr order by ocr");
		$ocr = [];
		while ($r = DB::getInstance()->nextRecord($q)) {
			$ocr[@$status[$r->ocr]] = $r->c;
		}

		$q = DB::getInstance()->query("select count(id) as c, idx from revision group by idx order by idx");
		$idx = [];
		while ($r = DB::getInstance()->nextRecord($q)) {
			$idx[@$status[$r->idx]] = $r->c;
		}

		return blade("status", ["spider" => $spider, "pdf" => $pdf, "ocr" => $ocr, "idx" => $idx]);
	}


	public static function api_get_idmatches() {
		return IDMatch::find([["id", ">=", 0]])->orderBy("weight")->all();
	}

	public static function api_add_idmatch($_request) {
		$i = new IDMatch;
		$i->example = $_request->put('example');
		$i->regex = $_request->put('regex');
		$i->weight = $_request->put('weight');
		$i->save();
		return SystemController::api_get_idmatches();
	}

	public static function api_set_idmatch($id) {
		$i = new IDMatch($id);
		if ($i) {
			$i->example = $_POST['example'];
			$i->regex = $_POST['regex'];
			$i->weight = $_POST['weight'];
			$i->save();
		}
		return SystemController::api_get_idmatches();
	}

	public static function api_del_idmatch($id) {
		$i = new IDMatch($id);
		if ($i) {
			$i->delete();
		}
		return SystemController::api_get_idmatches();
	}
}

