<?php

namespace TdyCommons\View\Strategy;

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

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

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

    /**
     * @param XlsxRenderer $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 XlsxRenderer|bool|null
     */
    public function selectRenderer(ViewEvent $e)
    {
        $model = $e->getModel();

        if (!$model instanceof XlsxModel) {
            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 XLSX
            return;
        }

        // Populate response
        /** @var HttpResponse $response */
        $response = $e->getResponse();
        $response->setContent($result);
        $response->getHeaders()->addHeaderLine('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    }
}