<?php

namespace Directus\Filesystem;

use Directus\Filesystem\Exception\ForbiddenException;
use League\Flysystem\FilesystemInterface as FlysystemInterface;

class Filesystem
{
    /**
     * @var FlysystemInterface
     */
    private $adapter;

    public function __construct(FlysystemInterface $adapter)
    {
        $this->adapter = $adapter;
    }

    /**
     * Check whether a file exists.
     *
     * @param string $path
     *
     * @return bool
     */
    public function exists($path)
    {
        return $this->adapter->has($path);
    }

    /**
     * Reads and returns data from the given location
     *
     * @param $location
     *
     * @return bool|false|string
     *
     * @throws \Exception
     */
    public function read($location)
    {
        return $this->adapter->read($location);
    }

    /**
     * Writes data to th given location
     *
     * @param string $location
     * @param $data
     * @param bool $replace
     */
    public function write($location, $data, $replace = false)
    {
        $throwException = function () use ($location) {
            throw new ForbiddenException(sprintf('No permission to write: %s', $location));
        };

        if ($replace === true && $this->exists($location)) {
            $this->getAdapter()->delete($location);
        }

        try {
            if (!$this->getAdapter()->write($location, $data)) {
                $throwException();
            }
        } catch (\Exception $e) {
            $throwException();
        }
    }

    /**
     * Get the filesystem adapter (flysystem object)
     *
     * @return FlysystemInterface
     */
    public function getAdapter()
    {
        return $this->adapter;
    }

    /**
     * Get Filesystem adapter path
     *
     * @param string $path
     * @return string
     */
    public function getPath($path = '')
    {
        $adapter = $this->adapter->getAdapter();

        if ($path) {
            return $adapter->applyPathPrefix($path);
        }

        return $adapter->getPathPrefix();
    }
}
