<?php
namespace Newland\Toubiz\Poi\Neos\OpeningTimes\Parser\KitchenTimes;

use Newland\Toubiz\Sync\Neos\Domain\Model\OpeningTimes\KitchenTime;

class LegacyFormatParser implements ParserInterface
{
    public function parse(string $openingTimes): array
    {
        $times = [];
        $data = json_decode($openingTimes);

        if ($data === null) {
            return $times;
        }

        foreach ($data->kitchen ?? [] as $entry) {
            $time = $this->initializeKitchenTime($entry);
            if ($time) {
                $times[] = $time;
            }
        }

        return $times;
    }

    private function initializeKitchenTime(\stdClass $entry): ?KitchenTime
    {
        $from = $this->dateTimeFromTime((string) $entry->from);
        $to = $this->dateTimeFromTime((string) $entry->to);

        if ($from === null || $to === null) {
            return null;
        } elseif ($from->format('H:i') === '00:00' && $to->format('H:i') === '00:00') {
            if (empty($entry->comment)) {
                return null;
            } else {
                return new KitchenTime(null, null, $entry->comment);
            }
        }

        return new KitchenTime($from, $to, $entry->comment);
    }

    private function dateTimeFromTime(string $time): ?\DateTime
    {
        $dateTime = \DateTime::createFromFormat('H:i:s', $time);
        if (!$dateTime) {
            return null;
        }
        return $dateTime->setDate(0, 1, 1);
    }
}
