<?php
/**
 * @author Colinet Julien
 */

namespace CpCreation\VitiCore\Bridge\Symfony\Bundle\Service\Uploader;

use Cocur\Slugify\Slugify;
use CpCreation\VitiCore\Bridge\Symfony\Bundle\Filesystem\ImageFilesystem;
use CpCreation\VitiCore\Media\Model\Image;
use League\Flysystem\Filesystem;
use Symfony\Component\HttpFoundation\File\UploadedFile;

class ImageUploader
{

    /**
     * @var Filesystem
     */
    private $filesystem;

    public function __construct(ImageFilesystem $filesystem)
    {
        $this->filesystem = $filesystem;
    }

    /**
     * @param UploadedFile $file
     * @return string
     */
    public function upload(UploadedFile $file)
    {
        $file = $this->uploadFile($file);

        return $file;
    }

    /**
     * @param UploadedFile $uploadedFile
     * @return Image
     *
     */
    private function uploadFile(UploadedFile $uploadedFile)
    {
        $slugify = new Slugify();
        $originalName = $uploadedFile->getClientOriginalName();
        $mimeType     = $uploadedFile->getClientMimeType();
        $size         = $uploadedFile->getSize();
        $fileName     = $slugify->slugify($originalName).'-'.substr(md5(uniqid()), 0, 5).'.'.$uploadedFile->guessExtension();
        $stream       = fopen($uploadedFile->getRealPath(), 'r+');
        $this->filesystem->writeStream($fileName, $stream);
        fclose($stream);

        $image = new Image();
        $image->setOriginalName($originalName);
        $image->setPath($fileName);
        $image->setMimeType($mimeType);
        $image->setSize($size);

        return $image;
    }
}

