<?php

class Revision extends Model {

	protected $_classes = [
		"document" => "Document"
	];

	protected $_computed = [
		"body" => "get_body",
	];

	protected $transform = [
		"info" => "json"
	];

	function path() {
		$rs = sprintf("%011d", $this->id);
		$d1 = substr($rs, 0, 2);
		$d2 = substr($rs, 2, 3);
		$d3 = substr($rs, 5, 3);
		$d4 = substr($rs, 8, 3);
		$p = sprintf("%s/pdf/%s/%s/%s/%s", ROOT, $d1, $d2, $d3, $d4);
		return $p;
	}

	function filename() {
		if ($this->document) {
			$out = $this->document->internal_id;
			if (($this->revno != "") && ($this->revno != "0")) {
				$out .= "-";
				$out .= $this->revno;
			}
			$out .= " ";
			$out .= $this->document->title . " " . $this->document->subtitle . " " . $this->document->subsubtitle;
		} else {
			$out = "doc";
		}
		$out = trim($out);
		$out.= ".pdf";
		$out = str_replace(" ", "_", $out);
		$out = str_replace("/", "_", $out);
		return $out;
	}

	function create_cover() {
		$p = $this->path();
		$pdf = new PDF($p . "/doc.pdf");
		$cover = $p . "/cover.jpg";
		$pdf->extract_page(0, $cover);
	}

	function cover($size = null) {
		$f = new File($this->path() . "/cover.jpg");
		if (!$f->exists()) {
			$this->create_cover();
		}
		if ($size == null) {
			return "/cover/" . $this->id . "/cover.jpg";
		}
		return "/cover/" . $this->id . "/" . $size . "/cover.jpg";
	}

	private $_body = null;

	public function get_body() {
		if ($this->_body == null) {
			$ocr = OCR::find([["revision", "=", $this->id]])->first();
			if (!$ocr) {
				return "";
			}
			$this->_body = $ocr->body;
		}
		return $this->_body;
	}

	public function get_page($page, $dpi = 300) {
		$file = new File(sprintf("%s/pages/%04d-%d.jpg", $this->path(), $page, $dpi));
		if ($file->exists()) {
			return new Image($file);
		}

		$dir = sprintf("%s/pages", $this->path());
		if (!file_exists($dir)) {
			mkdir($dir, 0777);
		}

		$pdf = new PDF(sprintf("%s/doc.pdf", $this->path()));
		$img = $pdf->extract_page($page, $file->path(), $dpi);

		if ($img) {
			return $img;
		}
		return null;
	}

	public function purge() {
		$dir = opendir($this->path());
		while ($file = readdir($dir)) {
			if (str_ends_with($file, ".jpg")) {
				unlink($this->path() . "/" . $file);
			}
		}
		closedir($dir);

		$dir = opendir($this->path() . "/pages");
		while ($file = readdir($dir)) {
			if (str_ends_with($file, ".jpg")) {
				unlink($this->path() . "/pages/" . $file);
			}
		}
		closedir($dir);
	}
}
