<?php

/**
 * ownCloud - Documents App
 *
 * @author Victor Dubiniuk
 * @copyright 2013 Victor Dubiniuk victor.dubiniuk@gmail.com
 *
 * This file is licensed under the Affero General Public License version 3 or
 * later.
 */

namespace OCA\Documents;

class DocumentController extends Controller{
	const ODT_TEMPLATE = '[encoded data, 11648 characters]';
	
	public static function create($args){
		$uid = self::preDispatch();
		
		$view = new \OC\Files\View('/' . $uid . '/files');
		
		$dir = \OCP\Config::getUserValue(\OCP\User::getUser(), 'documents', 'save_path', '/');
		if (!$view->is_dir($dir)){
			$dir = '/';
		}
		$path = Helper::getNewFileName($view, $dir . '/New Document.odt');
		
		$content = base64_decode(self::ODT_TEMPLATE);
		if (class_exists('\OC\Files\Type\TemplateManager')){
			$manager = \OC_Helper::getFileTemplateManager();
			$templateContent = $manager->getTemplate(Storage::MIMETYPE_LIBREOFFICE_WORDPROCESSOR);
			if ($templateContent){
				$content = $templateContent;
			}
		}
		
		if ($view->file_put_contents($path, $content)){
			$info = $view->getFileInfo($path);
			\OCP\JSON::success(array ('fileid' => $info['fileid']) );
		} else {
			\OCP\JSON::error(
					array ('message' => Config::getL10n()->t('Can\'t create document'))
			);
		}
	}


	/**
	 * Process partial/complete file download
	 * @param array $args - array containing session id as an element with a key es_id 
	 */
	public static function serve($args){
		$session = new Db\Session();
		$session->load(@$args['es_id']);
			
		self::preDispatchGuest();
		
		$filename = $session->getGenesisUrl() ? $session->getGenesisUrl() : '';
		$download = new Download($session->getOwner(), $filename);
		$download->sendResponse();
	}
	

	public static function rename($args){
		self::preDispatch();
		
		$fileId = intval(Helper::getArrayValueByKey($args, 'file_id', 0));
		$name = Helper::getArrayValueByKey($_POST, 'name');

		$view = \OC\Files\Filesystem::getView();
		$path = $view->getPath($fileId);

		if (isset($name) && $view->is_file($path) && $view->isUpdatable($path)) {
			$newPath = dirname($path) . '/' . $name;
			if ($view->rename($path, $newPath)) {
				\OCP\JSON::success();
				return;
			}
		}
		\OCP\JSON::error(array(
			'message' => Config::getL10n()->t('You don\'t have permission to rename this document')
		));
	}

	/**
	 * lists the documents the user has access to (including shared files, once the code in core has been fixed)
	 * also adds session and member info for these files
	 */
	public static function listAll(){
		self::preDispatch();
		
		$found = Storage::getDocuments();

		$fileIds = array();
		$documents = array();
		foreach ($found as $key=>$document) {
			if (is_object($document)){
				$documents[] = $document->getData();
			} else {
				$documents[$key] = $document;
			}
			$documents[$key]['icon'] = preg_replace('/\.png$/', '.svg', \OC_Helper::mimetypeIcon($document['mimetype']));
			$fileIds[] = $document['fileid'];
		}

		usort($documents, function($a, $b){
			return @$b['mtime']-@$a['mtime'];
		});
		
		$session = new Db\Session();
		$sessions = $session->getCollectionBy('file_id', $fileIds);

		$members = array();
		$member = new Db\Member();
		foreach ($sessions as $session) {			
			$members[$session['es_id']] = $member->getActiveCollection($session['es_id']);
		}

		\OCP\JSON::success(array('documents' => $documents,'sessions' => $sessions,'members' => $members));
	}
}
