<?php

declare(strict_types=1);

namespace Gls\GlsPoland\Soap\ExtSoapEngine\Wsdl;

use Gls\GlsPoland\Soap\ExtSoapEngine\Wsdl\Naming\Md5Strategy;
use Gls\GlsPoland\Soap\ExtSoapEngine\Wsdl\Naming\NamingStrategy;
use Gls\GlsPoland\Soap\Wsdl\Loader\WsdlLoaderInterface;
use Symfony\Component\Filesystem\Filesystem;

final class PermanentWsdlLoaderProvider implements WsdlProviderInterface
{
    /**
     * @var WsdlLoaderInterface
     */
    private $loader;
    /**
     * @var Filesystem
     */
    private $filesystem;
    /**
     * @var string
     */
    private $cacheDir;
    /**
     * @var NamingStrategy
     */
    private $namingStrategy;
    /**
     * @var bool
     */
    private $downloadForced = false;

    public function __construct(WsdlLoaderInterface $loader, Filesystem $filesystem, string $cacheDir, ?NamingStrategy $namingStrategy = null)
    {
        $this->loader = $loader;
        $this->filesystem = $filesystem;
        $this->namingStrategy = $namingStrategy ?? new Md5Strategy();
        $this->cacheDir = $cacheDir;
    }

    public function getWsdl(string $source): string
    {
        $file = $this->cacheDir . DIRECTORY_SEPARATOR . $this->namingStrategy->getFileName($source);
        if (!$this->downloadForced && $this->filesystem->exists($file)) {
            return $file;
        }

        $this->filesystem->dumpFile($file, $this->loader->load($source));

        return $file;
    }

    /**
     * Makes it possible to refresh permanently stored WSDL files.
     */
    public function forceDownload(): self
    {
        $new = clone $this;
        $new->downloadForced = true;

        return $new;
    }
}
