<?php

class Document extends Model {

	protected $_computed = [
		"related" => "get_related",
		"revisions" => "get_revisions",
		"products" => "get_products",
		"metadata" => "get_metadata",
		"attachments" => "get_attachments",
	];

	public function get_revisions() {
		return Revision::find([["document", "=", $this->id]])->orderBy("revno")->all();
	}

	public function get_related() {
		$revs = Revision::find([["document", "=", $this->id]])->all();
		$related = new Collection;
		foreach ($revs as $rev) {
			$q = DB::getInstance()->query("
				select 
					id,
					internal_id,
					title,
					subtitle,
					subsubtitle 
				from 
					document 
				where 
					internal_id in (
						select 
							distinct words.word 
						from 
							words,
							revwords 
						where 
							words.id=revwords.word 
						and 
							revwords.revision=:rev 
						and 
							words.word like '%-%-%'
			)", array("rev" => $rev->id));
			while ($r = DB::getInstance()->nextRecord($q)) {
				if ($r->id != $this->id) {
					$related->push(new Document($r->id));
				}
			}
		}
		return $related;
	}

    public function overview_md() {
        return \Michelf\Markdown::defaultTransform($this->overview);
    }

	public function on_delete() {
		DB::getInstance()->query("delete from docproduct where document=:id", ["id" => $this->id]);
	}

	private $_products = null;

	public function get_products() {
		if ($this->_products == null) {

			$this->_products = new Collection;
			$dpl = DocProduct::find([["document", "=", $this->id]])->all();
			foreach ($dpl as $dp) {
				$dp->load("product");
				$this->_products->push($dp->product);
			}
		}

		return $this->_products;
	}

	public function duplicate() {
		$newdoc = new Document();
		$newdoc->title = $this->title;
		$newdoc->subtitle = $this->subtitle;
		$newdoc->subsubtitle = $this->subsubtitle;
		$newdoc->overview = $this->overview;
		$newdoc->internal_id = $this->internal_id;
		$newdoc->owner = $this->owner;
		$newdoc->year = $this->year;
		$newdoc->month = $this->month;

		$newdoc->save();

		$dpl = DocProduct::find([["document", "=", $this->id]])->all();
		foreach ($dpl as $dp) {
			$ndp = new DocProduct();
			$ndp->document = $newdoc->id;
			$ndp->product = $dp->product;
			$ndp->save();
		}
		return $newdoc;
	}

	public function remove_product($id) {
		$dp = DocProduct::find([["document", "=", $this->id], ["product", "=", $id]])->first();
		if ($dp) {
			$dp->delete();
		}
	}

	public function set_metadata($metadata, $value) {
		$m = DocMeta::find([["document", "=", $this->id], ["metadata", "=", $metadata]])->first();
		if (!$m) {
			$m = new DocMeta();
			$m->document = $this->id;
			$m->metadata = $metadata;
		}
		$m->data = $value;
		$m->save();
		return $m->id;
	}

	public function get_metadata() {
        return DocMeta::find([["document", "=", $this->id]])->all();
	}

	public function remove_metadata($metadata) {
		$m = DocMeta::find([["document", "=", $this->id], ["metadata", "=", $metadata]])->first();
		if ($m) {
			$m->delete();
		}
	}

	public function get_metadata_by_id($metadata) {
		$m = DocMeta::find([["document", "=", $this->id], ["metadata", "=", $metadata]])->first();
		if (!$m) {
			return "";
		}
		return $m->data;
	}

	public function guess_docid() {
		$text = $this->title . " " . $this->subtitle . " " . $this->subsubtitle;
		$text .= $this->overview;

		$words = $this->get_words($text);

		return IDMatch::find_docid($words)[0];
	}


	function get_words($text) {
	    $text = str_replace("\r", " ", $text);
	    $text = str_replace("\n\n", "\n", $text);
	    $text = str_replace("\n\n", "\n", $text);
	    $text = str_replace("\n\n", "\n", $text);
	    $text = str_replace("\n\n", "\n", $text);
	    $text = str_replace("\n", " ", $text);
	    $text = str_replace("\"", "", $text);
	    $text = str_replace(",", " ", $text);
	    $text = str_replace("—", "-", $text);
	    $text = str_replace("~", "-", $text);
	    $text = str_replace("--", "-", $text);
	
	    $text = preg_replace('/([^a-zA-Z\-0-9]+)/', ' ', $text);
	
	    //$text = preg_replace("/([A-Za-z])(- )/", '$1', $text);
	
	    $words = preg_split('/\s+/', $text);
	    return $words;
	}


    function get_attachments() {
        $ap = ROOT . "/attachments/" . $this->id;
        $files = new Collection;
        if (!file_exists($ap)) {
            return $files;
        }
        if (!is_dir($ap)) {
            return $files;
        }

        $dir = opendir($ap);
        while ($f = readdir($dir)) {
            if (substr($f, 0, 1) == ".") continue;
            $f = new File($ap . "/" . $f);
            $files->push($f);
        }
    
        return $files;
    }


}
