<?php

namespace IZON\Thumber\ImageCache;

use IZON\Filesystem\FilesystemInterface;
use IZON\IO\File;
use IZON\IO\Image;
use IZON\IO\RasterImageInterface;
use IZON\Thumber\Exceptions\ImageNotInCacheException;

// DOTO-delel create interface

/**
 * Description of ImageCache
 *
 * @author lukas
 */
class ImageCache {

    /**
     * @var FilesystemInterface
     */
    protected $filesystem;
    /**
     * @var string
     */
    protected $dir;

    /**
     * ImageCache constructor.
     * @param FilesystemInterface $filesystem
     */
    public function __construct(FilesystemInterface $filesystem, string $dir) {
        $this->filesystem = $filesystem;
        $this->dir = $dir;
    }


    /**
     *
     * @param string $filename
     * @return bool
     */
    public function has(string $filename): bool {
      return $this->filesystem->has($filename);
    }

    /**
     *
     * @param string $filename
     * @return RasterImageInterface
     * @throws ImageNotInCacheException
     */
    public function get(string $filename): RasterImageInterface {
        if(!$this->filesystem->has($filename)) {
            throw new ImageNotInCacheException();
        }
        return $this->filesystem->getFile($filename);
    }

    /**
     *
     * @param string $filename
     * @return string
     * @throws ImageNotInCacheException
     */
    public function getPath(string $filename): string {
        if(!$this->filesystem->has($filename)) {
            throw new ImageNotInCacheException();
        }
        return "/". $this->getFilePath($filename);
    }

    /**
     *
     * @param string $filename
     * @param Image $image
     */
    public function set(string $filename, RasterImageInterface $image) {
        $this->filesystem->putStream($filename, $image->getFileStream());
    }

    protected function getFilePath($filename) {
        return $this->dir . (mb_substr($this->dir, -1) != '/' ? '/' : '') . $filename;
    }

}
