<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\PersonBundle\Validator\Constraints\Household;

use Chill\MainBundle\Util\DateRangeCovering;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

class MaxHolderValidator extends ConstraintValidator
{
    private const MAX_HOLDERS = 2;

    public function validate($household, Constraint $constraint)
    {
        $holders = $household->getMembersHolder();

        if ($holders->count() <= self::MAX_HOLDERS) {
            return;
        }

        $covers = new DateRangeCovering(
            self::MAX_HOLDERS,
            $holders->first()->getStartDate()->getTimezone()
        );

        foreach ($holders as $key => $member) {
            $covers->add($member->getStartDate(), $member->getEndDate(), $key);
        }

        $covers->compute();

        if ($covers->hasIntersections()) {
            foreach ($covers->getIntersections() as [$start, $end, $ids]) {
                $msg = null === $end ? $constraint->messageInfinity :
                    $constraint->message;

                $this->context->buildViolation($msg)
                    ->setParameters([
                        '{{ start }}' => $start->format('d-m-Y'), // TODO fix when MessageParameter works with timezone
                        '{{ end }}' => null === $end ? null : $end->format('d-m-Y'),
                    ])
                    ->addViolation();
            }
        }
    }
}
