<?php

namespace Velis\Mvc\View\Helper;

use Velis\App;
use Velis\Output;

/**
 * Dojo2 frontend app injector
 * @author Olek Procki <olo@velis.pl>
 */
class AppLayoutInjector
{
    /**
     * Returns token input field
     * @return string
     */
    public function __invoke()
    {
        $view = App::getService('view');

        if ($view->initFrontendApp) {
            $jsonData = file_get_contents(ROOT_PATH . 'public/app/output/' . (App::$config->layout->dojoMode ?: 'dist') . '/manifest.json');
            if ($jsonData) {
                $pathPrefix = '/app/output/' . (App::$config->layout->dojoMode ?: 'dist') . '/';
                $config = Output::jsonDecode($jsonData);

                return '<script type="text/javascript">
                            viewData = ' . Output::jsonEncode($view->getData()) . ';
                        </script>
                        <script type="text/javascript" src="' . $pathPrefix . $config['runtime.js'] . '"></script>
                        <script type="text/javascript" src="' . $pathPrefix . $config['main.js'] . '"></script>
                        <link rel="stylesheet" href="' . $pathPrefix . $config['main.css'] . '" type="text/css" />';
            }
        }
    }
}
