<?php

namespace AppBundle\Validator\Constraints;

use AppBundle\Entity\FewoReservation;
use AppBundle\Form\FewoReservationType;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

/**
 * Class FewoReservationValidator
 * @package AppBundle\Validator
 */
class FewoReservationValidator extends ConstraintValidator
{

    private function alreadyReserved($fromDate, $toDate, $reservationFromDate, $reservationToDate)
    {
        $result = true;

        if($fromDate >= $reservationToDate || $toDate <= $reservationFromDate)
        {
            $result = false;
        }

        return $result;
    }


    /**
     * Checks if the passed value is valid.
     *
     * @param FewoReservation $reservation The value that should be validated
     * @param Constraint $constraint The constraint for the validation
     */
    public function validate($reservation, Constraint $constraint)
    {
        $fromDate = $reservation->getFromDate();
        $toDate = $reservation->getToDate();


        $lodging = $reservation->getLodging();
        $reservations = $lodging->getReservations();
        $seasons = $lodging->getSeasons();

        $withinAnySeason = false;
        $alreadyReserved = false;

        for($i = 0; $i < count($seasons); $i++)
        {
            if($reservation->getFromDate() >= $seasons[$i]->getFromDate()
                && $reservation->getToDate() <= $seasons[$i]->getToDate())
            {
                $withinAnySeason = true;
            }
        }

        foreach($reservations as $reservation)
        {
            $reservationFromDate = $reservation->getFromDate();
            $reservationToDate = $reservation->getToDate();


            if($this->alreadyReserved($fromDate, $toDate, $reservationFromDate, $reservationToDate))
            {
                $alreadyReserved = true;
            }
        }

        if(!$withinAnySeason)
        {
            $this->context->buildViolation($constraint->message)
                ->addViolation();
        }

        if($alreadyReserved)
        {
            $this->context->buildViolation("Es gibt bereits Reservierungen innerhalb des gewünschten Zeitraums!")
                ->addViolation();
        }

    }
}