<?php

namespace IZON\Thumber\ImageCache;

use IZON\IO\File;
use IZON\IO\Image;
use IZON\Thumber\Exceptions\ImageNotInCacheException;

// DOTO-delel create interface

/**
 * Description of ImageCache
 *
 * @author lukas
 */
class ImageCache {
    /**
     *
     * @var string
     */
    protected $dir;

    /**
     * 
     * @param string $dir
     */
    function __construct(string $dir) {
        $this->dir = $dir;
    }

    /**
     * 
     * @param type $filename
     * @return bool
     */
    public function has($filename): bool {
        $file = new File($this->getFilePath($filename));
        return $file->exists();
    }

    /**
     * 
     * @param type $filename
     * @return Image
     * @throws ImageNotInCacheException
     */
    public function get($filename): Image {
        $file = new Image($this->getFilePath($filename));
        if(!$file->exists()) {
            throw new ImageNotInCacheException();
        }
        return $file;
    }

    /**
     * 
     * @param string $filename
     * @return string
     * @throws ImageNotInCacheException
     */
    public function getPath(string $filename): string {
        $file = new Image($this->getFilePath($filename));
        if(!$file->exists()) {
            throw new ImageNotInCacheException();
        }
        return $this->getFilePath($filename);
    }

    /**
     * 
     * @param string $filename
     * @param Image $image
     * @param bool $deleteSource default false
     */
    public function set(string $filename, Image $image, bool $deleteSource = false) {
        $filePath = $this->getFilePath($filename);
        if(!$this->has($filename)) {
            File::createFile($filePath);
        }
        $file = new File($filePath);
        \copy($image->getFsPath(), $file->getFsPath());
        if($deleteSource) {
            $image->delete();
        }
    }

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

}

