<?php

namespace Plainwork\Ui\Component\Form;

use Plainwork\Http\Request;
use Plainwork\Ui\Component\Form\AbstractFieldset;
use Plainwork\Ui\Component\Form\NumberInput;
use Plainwork\Ui\Component\Form\SelectInput;

class DatePeriodInput extends AbstractFieldset
{
    private ?NumberInput $inputQty = null;
    private ?SelectInput $inputUnit = null;

    private const RANGE_DAY = 'day';
    private const RANGE_WEEK = 'week';
    private const RANGE_MONTH = 'month';
    private array $range = [self::RANGE_WEEK, 1];
    // private int $d = 0;
    private string $value = '1w';

    public function getInputQty(): NumberInput
    {
        if (null === $this->inputQty) {
            $name = $this->getName();
            $this->inputQty = new NumberInput($name . '_qty');
        }

        return $this->inputQty;
    }

    public function getInputUnit(): SelectInput
    {
        if (null === $this->inputUnit) {
            $name = $this->getName();
            $options = ['d' => '__Day__', 'w' => '__Week__', 'm' => '__Month__'];
            $this->inputUnit = (new SelectInput($name . '_unit'))->setOptions($options);
        }

        return $this->inputUnit;
    }

    public function setValue(string $v): self
    {
        $this->value = $v;

        $qty = (int) substr($v, 0, -1);
        $unit = substr($v, -1);

        $this->getInputQty()->setValue($qty);
        $this->getInputUnit()->setValue($unit);

        return $this;
    }

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

    public function grab(Request $request)
    {
        $retQty = $this->getInputQty()->grab($request);
        $retUnit = $this->getInputUnit()->grab($request);

        $ret = $retQty . $retUnit;

        return $ret;
    }

    public static function expand(string $v): array
    {
        $qty = (int) substr($v, 0, -1);
        $range = substr($v, -1);
        $match = ['d' => 'day', 'w' => 'week', 'm' => 'month'];
        $period = $match[$range] ?? $match[current(array_keys($match))];

        return [$qty, $period];
    }
}
