<?php

namespace Plainwork\Ui\Component\Form;

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

class DurationInput extends AbstractFieldset
{
    private ?NumberInput $hourQty = null;
    private ?NumberInput $minuteQty = null;
    private ?int $value = 1*60*60;
    private bool $withHour = true;
    private bool $withMinute = true;
    private int $step = 1;

    public function withHour(bool $v): self
    {
        $this->withHour = $v;

        return $this;
    }

    public function withMinute(bool $v): self
    {
        $this->withMinute = $v;

        return $this;
    }

    public function getStep(): int
    {
        return $this->step;
    }

    public function setStep(int $step): self
    {
        $this->step = $step;

        return $this;
    }

    public function getHourQtyInput(): ?NumberInput
    {
        if (!$this->withHour) {
            return null;
        }

        if (null === $this->hourQty) {
            $name = $this->getName();
            $this->hourQty = (new NumberInput($name . '_hour'))
                ->setMin(0)
                ->setMax(24)
                ->setStep(1)
                ;
        }

        return $this->hourQty;
    }

    public function getMinuteQtyInput(): ?NumberInput
    {
        if (!$this->withMinute) {
            return null;
        }

        $max = $this->withHour ? 59 : null;
        $step = $this->getStep();

        if (null === $this->minuteQty) {
            $name = $this->getName();
            $this->minuteQty = (new NumberInput($name . '_minute'))
                ->setMin(0)
                ->setStep($step)
                ;

            if ($max) {
                $this->minuteQty->setMax($max);
            }

        }

        return $this->minuteQty;
    }

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

        if (null !== $v) {
            $minuteValue = ($v / 60) % 60;
            $hourValue = ($v - 60 * $minuteValue) / (60 * 60);

            $inp = $this->getHourQtyInput();
            if ($inp) {
                $inp->setValue($hourValue);
            }

            $inp = $this->getMinuteQtyInput();
            if ($inp) {
                $inp->setValue($minuteValue);
            }
        }

        return $this;
    }

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

    public function grab(Request $request): ?int
    {
        $inp = $this->getHourQtyInput();
        $hours = $inp ? $inp->grab($request) : null;

        $inp = $this->getMinuteQtyInput();
        $minutes = $inp ? $inp->grab($request) : null;

        if ((null === $hours) && (null === $minutes)) {
            return null;
        }

        $ret = 0;
        if (null !== $hours) {
            $ret += 60 * 60 * $hours;
        }
        if (null !== $minutes) {
            $ret += 60 * $minutes;
        }

        return $ret;
    }
}
