<?php

namespace Ignite\Core\Files\Processors;

use Ignite\Core\Contracts\Files\FileProcessor;
use Ignite\Core\Files\File;

class MoveFileProcessor implements FileProcessor
{
    /**
     * @var string
     */
    protected $directory;

    /**
     * @var string|null
     */
    protected $disk;

    /**
     * @var string|null
     */
    protected $name = null;

    /**
     * @param string $directory
     * @param string|null $disk If null, we will keep it on the same disk.
     */
    public function __construct(string $directory, ?string $disk = null)
    {
        $this->directory = rtrim($directory, '\\/').DIRECTORY_SEPARATOR;
        $this->disk = $disk;
    }

    /**
     * Change the name of the file as well.
     *
     * @param string $name
     * @return $this
     */
    public function withName(string $name): self
    {
        $this->name = $name;
        return $this;
    }

    /**
     * {@inheritdoc}
     * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
     */
    public function run(File $file): File
    {
        $newFile = new File(
            $this->directory.($this->name ?? $file->getBasename()),
            $this->disk ?? $file->getDisk()
        );

        $file->copyToFile($newFile);
        $file->delete();

        return $newFile;
    }
}
