<?php

namespace App\Service\Campaign\Report;

use App\Entity\Campaign\Report;
use App\Service\Campaign\ReportService;
use Exception;
use Knp\Snappy\Pdf;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpKernel\KernelInterface;
use Twig\Environment;
use Twig\Error\LoaderError;
use Twig\Error\RuntimeError;
use Twig\Error\SyntaxError;

class PdfService
{
    private $generator;
    /**
     * @var KernelInterface
     */
    private $kernel;
    /**
     * @var Environment
     */
    private $twig;
    /**
     * @var ReportService
     */
    private $reportService;
    /**
     * @var ElementService
     */
    private $elementService;
    /**
     * @var LoggerInterface
     */
    private $logger;

    public function __construct(Pdf $generator, KernelInterface $kernel, Environment $twig, ReportService $reportService, ElementService $elementService, LoggerInterface $logger)
    {
        $this->generator = $generator;
        $this->kernel = $kernel;
        $this->twig = $twig;
        $this->reportService = $reportService;
        $this->elementService = $elementService;
        $this->logger = $logger;
    }

    /**
     * @param Report $report
     *
     * @return string
     *
     * @throws Exception
     */
    public function generate(Report $report)
    {
        $elements = $this->elementService->getReportElements($report);

        try {
            $title = sprintf('%s', $report->getTitle());
            $html = $this->twig->render('Report/template.twig', ['widgets' => $elements, 'title' => $title]);
            $cover = $this->twig->render('Report/cover.twig', ['client' => $report->getCampaign()->getClient()
                ->getTitle(), 'title' => $title, ]);
            $this->logger->notice($html);
        } catch (LoaderError $e) {
            $this->logger->error($e->getMessage());
        } catch (RuntimeError $e) {
            $this->logger->error($e->getMessage());
        } catch (SyntaxError $e) {
            $this->logger->error($e->getMessage());
        }

        $file = substr(sha1(time()), 0, 10);

        $path = sprintf('%s/public/uploads/%s%s%s', $this->kernel->getProjectDir(), 'pdf/', $file, '.pdf');
        $this->generator->generateFromHtml($html, $path, compact('cover'));

        return $file.'.pdf';
    }
}
