<?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\Components\SubApplicationLoading\SubApplicationCodeGenerator;

use Shopware\Components\DependencyInjection\Container;
use Shopware\Plugins\ViisonCommon\Components\ControllerFactoryService;

class SmartySubApplicationCodeGenerator extends AbstractSubApplicationCodeGenerator
{
    /**
     * @var \Enlight_Plugin_PluginManager
     */
    private $pluginManager;

    /**
     * @param Container $dependencyContainer
     * @param \Enlight_Controller_Front $frontController
     * @param \Enlight_Loader $classLoader
     * @param \Enlight_Event_EventManager $eventEventManager
     * @param ControllerFactoryService $controllerFactoryService
     * @param \Enlight_Plugin_PluginManager $pluginManager
     * @param string $name
     * @param string $path
     * @param string $controllerClass
     */
    public function __construct(
        Container $dependencyContainer,
        \Enlight_Controller_Front $frontController,
        \Enlight_Loader $classLoader,
        \Enlight_Event_EventManager $eventEventManager,
        ControllerFactoryService $controllerFactoryService,
        \Enlight_Plugin_PluginManager $pluginManager,
        $name,
        $path,
        $controllerClass
    ) {
        parent::__construct(
            $dependencyContainer,
            $frontController,
            $classLoader,
            $eventEventManager,
            $controllerFactoryService,
            $name,
            $path,
            $controllerClass
        );
        $this->pluginManager = $pluginManager;
    }

    /**
     * @inheritdoc
     */
    public function generateSubApplicationCode()
    {
        /** @var \Enlight_Template_Manager $view */
        // Use legacy smarty rendering
        $view = clone $this->pluginManager->Controller()->ViewRenderer()->Action()->View();
        $view->loadTemplate($this->getTemplateForSubApp());
        foreach ($this->getViewParameters() as $key => $value) {
            $view->assign($key, $value);
        }

        return $view->render();
    }

    /**
     * Returns a Smarty template source consisting of all sub app files.
     *
     * @return string
     */
    private function getTemplateForSubApp()
    {
        $files = $this->getSubAppFiles();
        $files = array_unique($files);

        return sprintf('snippet:string:{include file="%s"}', implode("\"}\n{include file=\"", $files));
    }
}
