<?php declare(strict_types=1);
/*
 * irstea/php-cs-fixer-config - Jeux de règles pour php-cs-fixer.
 * Copyright (C) 2018-2020 IRSTEA
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 */

namespace Irstea\CS\HeaderComment;

use Irstea\CS\Composer\ComposerPackageInterface;

/**
 * Class SPDXLicenseTemplateProvider.
 */
final class SPDXLicenseTemplateProvider implements TemplateProviderInterface
{
    /**
     * @var ComposerPackageInterface
     */
    private $composerPackage;

    /**
     * @var string
     */
    private $urlTemplate;

    /**
     * SPDXLicenseTemplateProvider constructor.
     */
    public function __construct(ComposerPackageInterface $composerPackage, string $urlTemplate = 'https://spdx.org/licenses/%s.json')
    {
        $this->composerPackage = $composerPackage;
        $this->urlTemplate = $urlTemplate;
    }

    public function getTemplate(): ?string
    {
        $licenses = $this->composerPackage->getLicenses();

        foreach ($licenses as $id) {
            $template = $this->fetchTemplate($id);
            if ($template) {
                return $this->convertTemplate($template);
            }
        }

        return null;
    }

    private function fetchTemplate(string $spdxId): ?string
    {
        $licenseJson = @file_get_contents(sprintf($this->urlTemplate, $spdxId));
        if ($licenseJson === false) {
            return null;
        }

        $licenseInfo = json_decode($licenseJson, true);
        if ($licenseInfo === false || !isset($licenseInfo['standardLicenseHeader'])) {
            return null;
        }

        return $licenseInfo['standardLicenseHeader'];
    }

    private function convertTemplate(string $template): string
    {
        return preg_replace(
            '/<<var;name=("?)(.+?)\1;original=.+?;match=.+?>>/',
            '%%\2%%',
            preg_replace('/<<(begin|end)Optional>>/', '', $template)
        );
    }
}