<?php

namespace Plainwork\Ui\Renderer\Form;

use Plainwork\Http\Request;
use Plainwork\Ui\Ui;
use Plainwork\Ui\Component\HtmlElement;
use Plainwork\Ui\Component\Form\Button;

class ButtonRenderer
{
    public $ui = Ui::class;

    public function __invoke(Button $el, Request $request)
    {
        $name = $el->getName();

        $isDanger = $el->isDanger();
        $isPrimary = $el->isPrimary();

        $ret = new HtmlElement('button');

        $ret
            ->withAttr('name', $name)
            ->withAttr('value', 1)
            ;

        if ($isPrimary) {
            $ret->withAttr('type', 'submit');
        }
        if ($isDanger) {
            $ret->withAttr('onclick', "return confirm(\'__Are you sure__?\');");
        }

        $attr = $el->getAttr();
        foreach ($attr as $k => $v) {
            $ret->withAttr($k, $v);
        }

        $label = $el->getLabel();
        foreach (array_keys($label) as $ii) {
            if (is_array($label[$ii]) && (null !== $path_)) {
                $request_ = $this->requestFactory->from($request, $path_, $params);
                $label[$ii] = $this->app->call($label[$ii], $request_);
            }
        }

    // render each part of the label
        $iis = array_keys($label);
        foreach ($iis as $ii) {
            $label[$ii] = $this->ui->render($label[$ii], $request);
            if (null === $label[$ii]) {
                unset($label[$ii]);
            }
        }

        if (count($label) > 1) {
            $iis = array_keys($label);
            foreach ($iis as $ii) {
                if ('<' !== substr($label[$ii], 0, 1)) {
                    $label[$ii] = '<span>' . $label[$ii] . '</span>';
                }
            }
            $label = '<span class="pw-label">' . join('', $label) . '</span>';
            $el->withAttr('class', 'pw-multipart-el');
        } else {
            $label = current($label);
            $label = $this->ui->render($label, $request);
        }

        $ret->append($label);

        return $ret;
    }
}
