<?php
namespace carabi_cms;

/**
 * Carabi Document Editor
 * 
 * Частично скопировано с pagehandler_panel
 *
 * @author sasha
 */
class DocumentEditor {
	/**
	 * Инициализация редактора документов
	 * @param mixed $initArgument ID (для редактирования) или тип (для создания) документа
	 * @param string $argumentType тип $initArgument: documentId или documentType
	 * @return \CarabiEditor 
	 */
	protected static function init_documentEditor($initArgument, $argumentType = "documentId") {
		require_once CARABI_DIR . "/classes/document_editor/CarabiEditor.php";
		if (defined("SUB_URL")) {
			$subUrl = SUB_URL;
		}
		$carabiEditor = new \CarabiEditor();
		$carabiEditor->setConfig('haru_config1');
		if ($argumentType == "documentId") {
			$documentId = $initArgument;
			$carabiEditor->setMainDocument((int)$documentId);
		} else if ($argumentType == "documentType") {
			$documentId = -1;
			$document = new \SimpleDocument($documentId, $initArgument);
			$carabiEditor->setMainDocument($document);
		}
		$carabiEditor->setConfigValue('connectorUrl', $subUrl . '/panel/index.aspx');
		$carabiEditor->setConfigValue('connectorPrefix', "a=dE&d={$documentId}");

		return $carabiEditor;
	}
	
	/**
	 * Запуск редактора документов
	 * @param mixed $initArgument ID (для редактирования) или тип (для создания) документа
	 * @param string $template шаблон Smarty для отображения документа
	 */
	private static function doDocumentEditor($initArgument, $template) {
		if (empty($initArgument)) {
			throw new Exception("Empty init argument for document editor");
		}
		if ((int)$initArgument > 0 ) {
			$argumentType = "documentId";
		} else {
			$argumentType = "documentType";
		}
		$documentEditor = self::init_documentEditor($initArgument, $argumentType);
		if ($documentEditor->isSelfRequest()) {
			$documentEditor->processRequest();
		} else {
			$render = \utls::get_renderer();
			$tpl = $render->createTemplate($template);
			$tpl->assignByRef('dE', $documentEditor->fetchWidget());
			return $tpl;
		}
	}

	public static function editDocument($documentId, $template='carabi_cms/_de.tpl') {
		if (empty($documentId)) {
			throw new Exception('Wrong document id');
		}
		return self::doDocumentEditor($documentId, $template);
	}
	
	public static function createNewDocument($documentType) {
		if (empty($documentType)) {
			throw new Exception('Wrong document type');
		}
		return create_document($documentType);
	}
	
	public static function deleteDocument($documentID) {
		ora_proc("documents.DOCF_DELETE_2('$documentID', true)");
	}
}
?>
