<?php

namespace Plainwork\Ui\Renderer;

use Plainwork\Core\Translate;
use Plainwork\Http\Request;
use Plainwork\Http\Uri;
use Plainwork\Ui\Ui;
use Plainwork\Ui\Component\Main;

final class PrintViewMainRendererDecorator
{
    public $translate = Translate::class;
    public $ui = Ui::class;
    public $uri = Uri::class;

    public function __invoke(Main $el, Request $request, callable $next)
    {
        $nextRet = ($next)($el, $request);

        $isPrintView = ('print' === $request->queryParam('layout-')) ? true : false;
        if (!$isPrintView) {
            return $nextRet;
        }

        $ret = [];

        $ret[] = '<!DOCTYPE html>';
        $ret[] = '<html xmlns="http://www.w3.org/1999/xhtml">';
        $ret[] = '<head>';
        $ret[] = '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
        $ret[] = '<meta name="viewport" content="width=device-width, initial-scale=1">';

        $ret[] = '<title>';

        $title = $el->title;
        $title = $this->ui->render($title, $request);
        $title = $this->translate->translate($title);

        $title = strip_tags($title);
        $ret[] = esc_html($title);

        // $title = $this->ui->render($el->getTitle(), $request);
        // $title = $this->translate->translate($title);
        // $title = strip_tags($title);
        // $ret[] = esc_html($title);

        $ret[] = '</title>';

        $css = $el->getCss();
        array_unshift($css, 'assets/plainwork/ui/print.css');
        array_unshift($css, 'assets/plainwork/ui/core.css');
        foreach ($css as $f) {
            $ret[] = '<link rel="stylesheet" type="text/css" href="' . $this->uri->asset($f) . '">';
        }

        // $js = $el->getJs();
        // _print_r($js);
        // exit;
        // foreach ($js as $f) {
            // $ret[] = '<script language="JavaScript" src="' . $this->uri->asset($f) . '"></script>';
        // }

        $ret[] = '</head>';

        $ret[] = '<body>';
        $ret[] = $this->ui->render($nextRet, $request);
        $ret[] = '</body>';

        $ret[] = '</html>';

        $ret = join('', $ret);

        return $ret;
    }
}
