<?php
// Copyright (c) Pickware GmbH. All rights reserved.
// This file is part of software that is released under a proprietary license.
// You must not copy, modify, distribute, make publicly available, or execute
// its contents or parts thereof without express permission by the copyright
// holder, unless otherwise permitted by law.

namespace Shopware\Plugins\ViisonCommon\Classes\Document\RenderedDocument;

use Shopware\Plugins\ViisonCommon\Classes\Exceptions\FileSystemExceptions\DirectoryNotWritableException;
use Shopware\Plugins\ViisonCommon\Classes\Util\Util;
use Shopware\Plugins\ViisonCommon\Components\FileStorage\FileStorage;

/**
 * Immutable class comprising the HTML and PDF rendering results of an AbstractRenderingContext.
 */
class RenderedDocument
{
    /**
     * @var string
     */
    protected $html;

    /**
     * @var string
     */
    protected $pdf;

    /**
     * @internal Is only called by AbstractRenderingContext
     *
     * @param string $html
     * @param string $pdf
     */
    public function __construct($html, $pdf)
    {
        $this->html = $html;
        $this->pdf = $pdf;
    }

    /**
     * @return string The HTML output of an AbstractRenderingContext
     */
    public function getHtml()
    {
        return $this->html;
    }

    /**
     * @return string The PDF output of an AbstractRenderingContext
     */
    public function getPdf()
    {
        return $this->pdf;
    }

    /**
     * Writes the PDF content as file to disk
     *
     * @param string $fileName Path to the destination file
     * @return int|bool The number of bytes that were written to the file, or false on failure.
     * @throws DirectoryNotWritableException When the path at $fileName is not writable
     */
    public function savePdfAsFile($fileName)
    {
        if (!is_writable(dirname($fileName))) {
            throw new DirectoryNotWritableException($fileName);
        }

        return file_put_contents($fileName, $this->pdf);
    }

    /**
     * Saves generated PDF to given FileStorage.
     *
     * @param FileStorage $fileStorage
     * @param string $fileName
     */
    public function savePdfToFileStorage(FileStorage $fileStorage, $fileName)
    {
        $fileStorage->writeFileContents($fileName, $this->pdf);
    }

    /**
     * Sends the PDF response to the browser
     *
     * All required headers are set automatically.
     *
     * @param \Enlight_Controller_Response_ResponseHttp $response
     * @param string $displayName
     */
    public function sendPdfAsHttpResponse(\Enlight_Controller_Response_ResponseHttp $response, $displayName)
    {
        Util::respondWithPDF($response, $this->pdf, $displayName);
    }
}
