<?php
namespace Backend\BaseBundle\FileStore;
use Aws\S3\S3Client;
use JMS\DiExtraBundle\Annotation as DI;

/**
 * @DI\Service("file_store.s3")
 */
class FileStoreS3 implements FileStoreInterface
{

    protected $bucket;

    /** @var  S3Client */
    protected $client;
    protected $uidGenerator;

    public function __construct()
    {
        $this->uidGenerator = new Uid\RandomUidGenerator(static::class);
    }

    /**
     * @DI\InjectParams({
     *     "bucket" = @DI\Inject("%aws_s3_bucket%")
     * })
     */
    public function injectBucket($bucket)
    {
        $this->bucket = $bucket;
    }

    /**
     * @DI\InjectParams({
     *     "client" =  @DI\Inject("aws.s3", required = false)
     * })
     */
    public function injectS3Client(S3Client $client = null)
    {
        $this->client = $client;
    }

    /**
     * @param string $uid
     * @param string $suffix
     * @param string $ext
     * @param string $pathName
     * @return bool
     */
    public function write($uid, $suffix, $ext, $pathName)
    {
        $this->client->putObject(array(
            'Bucket' => $this->bucket,
            'Key' => "$uid.$suffix.$ext",
            'Body' => fopen($pathName, 'r+'),
            'ACL' => 'public-read',
        ));
    }

    /**
     * @param string $uid
     * @param string $suffix
     * @param string $ext
     * @return bool
     */
    public function delete($uid, $suffix, $ext)
    {
        $this->client->deleteObject(array(
            'Bucket' => $this->bucket,
            'Key' => "$uid.$suffix.$ext",
        ));
    }

    /**
     * @return string
     */
    public function generateUid()
    {
        return $this->uidGenerator->generate();
    }

    public function webPath($uid)
    {
        return null;
    }
}