<?php

namespace Plainwork\Ui\Renderer\Form;

use Plainwork\Http\Request;
use Plainwork\Ui\Component\Form\TimeInput;
use Plainwork\Ui\Component\Form\SelectInput;
use Plainwork\Ui\Component\InlineList;
use Plainwork\Ui\Ui;
use Plainwork\DateTime\DateTimeFormatter;

class TimeInputRenderer
{
    public $ui = Ui::class;
    public $dtf = DateTimeFormatter::class;

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

        $valueH = floor($value / (60 * 60));
        $valueM = floor(($value - $valueH * (60 * 60)) / 60);

        $dt = new \DateTime();

        $options = [];
        foreach (range(0, 23, 1) as $k) {
            $v = $k;

            $dt->setTime($k, 0);
            $v2 = $this->dtf->formatHour($dt);

            $v = sprintf('%02d', $k);
            $options[$k] = $v2;
        }
        $inputHour = (new SelectInput($name . '_h'))
            ->setOptions($options)
            ->setValue($valueH)
            ->withAttr('style', ['min-width' => '6em'])
            ;

        $options = [];
        $step = $el->getStep();
        for ($k = 0; $k < 60; $k += $step) {
            $v = sprintf('%02d', $k);
            $options[$k] = $v;
        }

        $inputMinute = (new SelectInput($name . '_m'))
            ->setOptions($options)
            ->setValue($valueM)
            ->withAttr('style', ['min-width' => '4em'])
            ;

        $ret = (new InlineList())
            ->add($inputHour)
            ->add(':')
            ->add($inputMinute)
            ;

        return $ret;
    }
}
