<?php
/**
 * Copyright 2020 Adobe
 * All Rights Reserved.
 *
 * NOTICE: Adobe permits you to use, modify, and distribute this file in
 * accordance with the terms of the Adobe license agreement accompanying
 * it.
 */
declare(strict_types=1);

namespace Sut\Domain\Compatibility\Output;

use DateTime;
use Exception;
use Sut\Domain\Compatibility\Data\AnalysisResult;
use Sut\Domain\Compatibility\Output\Html\Render;
use Sut\Domain\Compatibility\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;

class Html implements OutputInterface
{
    /**
     * @var Render
     */
    private $render;

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

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

    /**
     * @param Render $render
     * @param string $defaultOutputPath
     * @param string $documentationLink
     */
    public function __construct(Render $render, string $defaultOutputPath, string $documentationLink)
    {
        $this->render = $render;
        $this->defaultOutputPath = $defaultOutputPath;
        $this->documentationLink = $documentationLink;
    }

    /**
     * @param SymfonyStyle $output
     * @param AnalysisResult $analysisResult
     */
    public function write(
        SymfonyStyle $output,
        AnalysisResult $analysisResult
    ): void {
        $outputPath = $analysisResult->getAnalysisRequest()->getHtmlOutputPath()
            ?? sprintf($this->defaultOutputPath, (new DateTime())->format('d_M_Y_H:i'));

        $content = $this->render->execute($analysisResult, $this->documentationLink);
        try {
            (new SaveFile())->execute($outputPath, $content);
        } catch (Exception $exception) {
            $output->writeln("<error>" . $exception->getMessage() . "</error>");
            return;
        }

        $output->writeln(sprintf("<comment>HTML report saved to '%s'</comment>", $outputPath));
    }
}
