<?php

namespace Plainwork\Ui\Component\Form;

use Plainwork\Http\Request;
use Plainwork\Ui\Component\Form\CheckboxInput;
use Plainwork\Ui\Component\Form\AbstractFieldset;

class CheckboxSetInput extends AbstractFieldset
{
    private array $options = [];
    private array $value = [];
    private array $disabledOptions = [];
    public bool $isVertical = false;
    public bool $freeOptions = false;

    public function setVertical(bool $v = true): self
    {
        $this->isVertical = true;

        return $this;
    }

    public function getOne($k)
    {
        if (!array_key_exists($k, $this->options)) {
            return;
        }

        $ret = new CheckboxInput($this->getName() . '[]');
        $ret->setHtmlValue($k);

        return $ret;
    }

    public function getOptions(): array
    {
        return $this->options;
    }

    public function setOptions(array $v): self
    {
        $this->options = $v;

        return $this;
    }

    public function setDisabledOptions(array $k): self
    {
        $this->disabledOptions = $k;

        return $this;
    }

    public function getDisabledOptions(): array
    {
        return $this->disabledOptions;
    }

    public function grab(Request $request): array
    {
        $options = $this->getOptions();
        if ($this->isRequired() && (count($options) < 2)) {
            return array_keys($options);
        }

        $ret = $request->getPostParam($this->getName()) ?? [];
        if (!$this->freeOptions) {
            $ret = array_intersect($ret, array_keys($this->options));
        }

        if ($this->isRequired() && (!$ret)) {
            $this->addError($this->getRequiredLabel());
        }

        return $ret;
    }

    public function setValue(array $v): self
    {
        if (!$this->freeOptions) {
            $v = array_intersect($v, array_keys($this->options));
        }
        $this->value = $v;

        return $this;
    }

    public function getValue(): array
    {
        return $this->value;
    }
}
