<?php


class ZasobFileOdt {

	var $zasob_id;
	var $druk_zasob_id;
	var $base_path;
	var $xsl_file;
	var $odt_file;
	var $content;

	function __construct($zasob_id, $base_path, $xsl_path, $druk_zasob_id = null) {
		$this->zasob_id = $zasob_id;
		$this->druk_zasob_id = ($druk_zasob_id)? $druk_zasob_id : $zasob_id;
		$this->base_path = $base_path;
		$this->xsl_path = $xsl_path;
		$this->odt_file = '';
		$this->xsl_file = '';
		$this->content = '';
	}

	function find_odt_file() {
		$tmp_druki = array();
		$tmp_druki = glob("{$this->base_path}/{$this->zasob_id}.*/{$this->druk_zasob_id}.*.odt", GLOB_NOSORT);
		if (empty($tmp_druki)) {
			return false;
		}
		if (count($tmp_druki) == 1) {
			$this->odt_file = reset($tmp_druki);
		} else {
			// TODO: sort by date and get first?
			$this->odt_file = end($tmp_druki);
		}

		if (!$this->odt_file) {
			return false;
		}
		return true;
	}

	function find_xsl_file() {
		$tmp_druki = glob("{$this->xsl_path}/{$this->zasob_id}.*.xsl", GLOB_NOSORT);
		if (empty($tmp_druki)) {
			return false;
		}
		if (count($tmp_druki) == 1) {
			$this->xsl_file = reset($tmp_druki);
		} else {
			// TODO: sort by date and get first?
			$this->xsl_file = end($tmp_druki);
		}

		if (!$this->xsl_file) {
			return false;
		}
		return true;
	}

	/**
	 * @param $converter - require methods: oo_unzip(odt_file); oo_convert(unzip, xsl_file);
	 */
	function fetch_content_from_odt_by_converter($converter) {
		$conv = new Odt2xhtml;
		$this->content = $converter->oo_convert($converter->oo_unzip($this->odt_file), $this->xsl_file);
		if (empty($this->content)) {
			return false;
		}
	}

	function add_data($data) {
		if (empty($this->content)) {
			return;
		}
		foreach ($data as $k_field => $v_value) {
			$this->content = str_replace('<span id="cell-'.$k_field.'"></span>', $v_value, $this->content);
		}
	}

	function get_content() {
		return $this->content;
	}

}
