<?php

namespace Plainwork\Ui\Middleware;

use Plainwork\Http\Request;
use Plainwork\Http\Redirect;
use Plainwork\Ui\Component\Main;
use Plainwork\Ui\FlashMessenger;

final class FlashMessageMiddleware
{
    public $flashMessenger = FlashMessenger::class;

    public function __invoke(Request $request, callable $next)
    {
        $ret = $next($request);

        if ($ret instanceof Redirect) {
            $msgs = $ret->getMessages();
            if ($msgs) {
                $msgIds = [];
                foreach ($msgs as $msg) {
                    $msgId = $this->flashMessenger->getMessageId($msg);
                    if (null !== $msgId) {
                        $msgIds[] = $msgId;
                    }
                }
                if ($msgIds) {
                    $ret = $ret->withParam('msg-', join('-', $msgIds));
                }
            }

            return $ret;
        }

        if ($ret instanceof Main) {
            $msgIds = $request->getQueryParam('msg-');
            if (null !== $msgIds) {
                $msgIds = explode('-', $msgIds);
                foreach ($msgIds as $msgId) {
                    $msg = $this->flashMessenger->getMessageById($msgId);
                    if ($msg) {
                        $ret = $ret->withMessage($msg);
                    }
                }
            }
        }

        return $ret;
    }
}
