<?php

namespace Ignite\Core\Files\Processors;

use Ignite\Core\Contracts\Files\FileEncrypter;
use Ignite\Core\Contracts\Files\FileProcessor;
use Ignite\Core\Facades\FileEncryption;
use Ignite\Core\Files\File;
use Ignite\Core\Files\TemporaryFileBuilder;

class DecryptFileProcessor implements FileProcessor
{
    /**
     * @var FileEncrypter
     */
    protected $fileEncrypter;

    /**
     * By default, the destination will be the same file.
     *
     * @var File|null
     */
    protected $destinationFile = null;

    /**
     * @param FileEncrypter|string|null $fileEncrypter
     */
    public function __construct($fileEncrypter = null)
    {
        $this->fileEncrypter = $fileEncrypter instanceof FileEncrypter
            ? $fileEncrypter
            : FileEncryption::encrypter($fileEncrypter);
    }

    /**
     * Set where we should save the encrypted version of the file.
     *
     * @param File $file
     * @return $this
     */
    public function destination(File $file): self
    {
        $this->destinationFile = $file;
        return $this;
    }

    /**
     * Save to a temporary location.
     *
     * @return $this
     */
    public function toTemporary(): self
    {
        return $this->destination(TemporaryFileBuilder::start()->prefix($this)->make());
    }

    /**
     * {@inheritdoc}
     */
    public function run(File $file): File
    {
        return $this->fileEncrypter->decrypt($file, $this->destinationFile ?? $file);
    }
}
