<?php

namespace Plainwork\Ui\Middleware;

use Plainwork\Http\Request;
use Plainwork\Http\Redirect;
use Plainwork\Http\Response;
use Plainwork\Ui\Ui;

class UiMiddleware
{
    public $ui = Ui::class;
    private $layoutParamName = 'layout-';

    public function __invoke(Request $request, callable $next)
    {
        $ret = $next($request);
        if ($ret instanceof Response) {
            return $ret;
        }

        $requestedLayoutId = $request->getQueryParam($this->layoutParamName) ?? '';

    // keep layout param with redirect
        if (strlen($requestedLayoutId)) {
            if ($ret instanceof Redirect) {
                $ret = $ret->withParam($this->layoutParamName, $requestedLayoutId);
            }

            $isPrintView = ('print' == $requestedLayoutId) ? true : false;
            if ($isPrintView) {
                $this->ui->setPrintView(true);
            }
        }

        if (strlen($requestedLayoutId)) {
            $request = $request->withAttribute('layoutId', $requestedLayoutId);
        }

        if (!is_object($ret)) {
            return $ret;
        }

        $ret = $this->ui->render($ret, $request);

        return $ret;
    }
}
