<?php

namespace TdyCommons\View\Strategy;

use TdyCommons\View\Model\PdfModel;
use TdyCommons\View\Renderer\PdfRenderer;
use Zend\EventManager\AbstractListenerAggregate;
use Zend\EventManager\EventManagerInterface;
use Zend\Http\Response as HttpResponse;
use Zend\View\ViewEvent;

/**
 * Class PdfStrategy
 *
 * @package TdyCommons\View\Strategy
 */
class PdfStrategy extends AbstractListenerAggregate
{
    protected $charset = 'utf-8';

    /**
     * @var PdfRenderer
     */
    protected $renderer;

    /**
     * @param PdfRenderer $renderer
     */
    public function __construct($renderer = null)
    {
        $this->renderer = $renderer;
    }

    /**
     * @param EventManagerInterface $events
     * @param int                   $priority
     */
    public function attach(EventManagerInterface $events, $priority = 1)
    {
        $this->listeners[] = $events->attach(ViewEvent::EVENT_RENDERER, array($this, 'selectRenderer'), $priority);
        $this->listeners[] = $events->attach(ViewEvent::EVENT_RESPONSE, array($this, 'injectResponse'), $priority);
    }

    /**
     * @param $charset
     *
     * @return $this
     */
    public function setCharset($charset)
    {
        $this->charset = (string) $charset;

        return $this;
    }

    /**
     * @return string
     */
    public function getCharset()
    {
        return $this->charset;
    }

    /**
     * @param ViewEvent $e
     *
     * @return PdfRenderer|bool|null
     */
    public function selectRenderer(ViewEvent $e)
    {
        $model = $e->getModel();

        if (!$model instanceof PdfModel) {
            return null;
        }

        return $this->renderer;
    }

    public function injectResponse(ViewEvent $e)
    {
        $renderer = $e->getRenderer();

        if ($renderer !== $this->renderer) {
            // Discovered renderer is not ours; do nothing
            return;
        }

        $result = $e->getResult();

        if (!is_string($result)) {
            // We don't have a string, and thus, no PDF
            return;
        }

        // Populate response
        /** @var HttpResponse $response */
        $response = $e->getResponse();
        $response->setContent($result);
        $response->getHeaders()->addHeaderLine('Content-Type', 'application/pdf');
        $response->getHeaders()->addHeaderLine('Content-Disposition', 'inline');

    }
}