<?php

namespace FiloBlu\Flow\Model\Manager;

use Magento\Catalog\Model\Product\Media\Config;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Exception\FileSystemException;
use Magento\Framework\Filesystem;
use Magento\Framework\Filesystem\Directory\WriteInterface;
use Magento\Framework\Filesystem\Driver\File;
use Magento\MediaStorage\Model\File\Uploader;

/**
 * Class ProductImageManager
 */
class ProductImageManager
{

    /**
     * @var Filesystem
     */
    private $filesystem;
    /**
     * @var Config
     */
    private $config;
    /**
     * @var array
     */
    private $cacheDirectories = [];

    /**
     * @var File
     */
    private $driverFile;

    /**
     * ImageManager constructor.
     * @param Filesystem $filesystem
     * @param Config $config
     * @param File $driverFile
     */
    public function __construct(
        Filesystem $filesystem,
        Config $config,
        File $driverFile

    )
    {
        $this->filesystem = $filesystem;
        $this->config = $config;
        $this->driverFile = $driverFile;
    }

    /**
     * @param $imageName
     * @throws FileSystemException
     */
    public function cleanCache($imageName)
    {
        $relativePath = Uploader::getDispretionPath($imageName) . DIRECTORY_SEPARATOR . $imageName;
        foreach ($this->getCacheDirectories() as $directory) {
            @unlink("{$directory}{$relativePath}");
        }
    }

    /**
     * @throws FileSystemException
     */
    public function getCacheDirectories(): array
    {
        if (!empty($this->cacheDirectories)) {
            return $this->cacheDirectories;
        }

        /** @var WriteInterface $directory */
        $directory = $this->filesystem->getDirectoryWrite(DirectoryList::MEDIA);
        $directoryPath = $directory->getAbsolutePath($this->config->getBaseMediaPath() . DIRECTORY_SEPARATOR . DirectoryList::CACHE);

        $files = $this->driverFile->readDirectory($directoryPath);
        foreach ($files as $file) {
            if (!$this->driverFile->isDirectory($file)) {
                continue;
            }

            if (strpos($file, '.', 0) === 0) {
                continue;
            }
            $this->cacheDirectories[] = $file;
        }

        return $this->cacheDirectories;
    }
}
