<?php
/**
 * 这个是kunbei 写的通讯录存储目录。
 * 主要提供给 app端保存数据
 */
namespace OCA\DAV\Vcf;

use OC\Files\Filesystem;
use OC\Files\View;
use OCA\DAV\Connector\Sabre\Directory;
use Sabre\DAV\Exception\Forbidden;
use Sabre\DAV\ICollection;

class VcfHome implements ICollection {
	/**
	 * UploadHome constructor.
	 *
	 * @param array $principalInfo
	 */
	public function __construct($principalInfo) {
		$this->principalInfo = $principalInfo;
	}

	function createFile($name, $data = null) {
		throw new Forbidden('Permission denied to create file (filename ' . $name . ')');
               // $this->impl()->createFile($name, $data);
	}

	function createDirectory($name) {
		$this->impl()->createDirectory($name);
	}

	function getChild($name) {
		return new VcfFolder($this->impl()->getChild($name));
	}

	function getChildren() {
		return array_map(function($node) {
			return new VcfFolder($node);
		}, $this->impl()->getChildren());
	}

	function childExists($name) {
		return !is_null($this->getChild($name));
	}

	function delete() {
		$this->impl()->delete();
	}

	function getName() {
		list(,$name) = \Sabre\Uri\split($this->principalInfo['uri']);
		return $name;
	}

	function setName($name) {
		throw new Forbidden('Permission denied to rename this folder');
	}

	function getLastModified() {
		return $this->impl()->getLastModified();
	}

	/**
	 * @return Directory
	 */
	private function impl() {
		$rootView = new View();
		$user = \OC::$server->getUserSession()->getUser();
		Filesystem::initMountPoints($user->getUID());
		if (!$rootView->file_exists('/' . $user->getUID() . '/vcfs')) {
			$rootView->mkdir('/' . $user->getUID() . '/vcfs');                       
		}
                if (!$rootView->file_exists('/' . $user->getUID() . '/vcfs/card')) {
                     $rootView->mkdir('/' . $user->getUID() . '/vcfs/card');
                }
		$view = new View('/' . $user->getUID() . '/vcfs');
		$rootInfo = $view->getFileInfo('');
		return new Directory($view, $rootInfo);
	}
}
