<?php

namespace Webapp\FileManagement\Service;

use Doctrine\ORM\EntityManagerInterface;
use Vich\UploaderBundle\Storage\StorageInterface;
use Webapp\FileManagement\Entity\Base\UserLinkedFileJob;

/**
 * Class AbstractFileService.
 */
abstract class AbstractFileService
{
    private string $tmpDir;

    protected StorageInterface $storage;

    protected EntityManagerInterface $entityManager;

    protected DirectoryNamer $directoryNameManager;

    public function __construct(EntityManagerInterface $entityManager,
                                DirectoryNamer         $directoryNameManager,
                                StorageInterface       $storage,
                                string                 $tmpDir)
    {
        $this->entityManager = $entityManager;
        $this->directoryNameManager = $directoryNameManager;
        $this->storage = $storage;
        $this->tmpDir = $tmpDir;
    }

    /**
     * @param UserLinkedFileJob $projectFile
     * @return string
     */
    protected function getTmpDir(UserLinkedFileJob $projectFile): string
    {
        $directory = $this->tmpDir . '/' . $this->directoryNameManager->directoryName($projectFile);;
        if (!is_dir($directory)) {
            mkdir($directory, 0777, true);
        }
        return $directory;
    }

    /**
     * @param UserLinkedFileJob $projectFile
     */
    protected function cleanTmpDir(UserLinkedFileJob $projectFile)
    {
        $directory = $this->getTmpDir($projectFile);
        $callback = function (string $file) use (&$callback) {
            if (is_dir($file)) {
                array_map($callback, glob($file . '/' . '*'));
                rmdir($file);
            } else {
                unlink($file);
            };
        };
        array_map($callback, glob($directory . '/' . '*'));
        rmdir($directory);
    }
}
