<?php

namespace CouponsPlus\App\Coupon\Attributes;

use CouponsPlus\Original\Collections\Collection;
use CouponsPlus\app\coupon\attributes\abilities\AttributeValueData;
use CouponsPlus\App\Coupon\Attributes\Abilities\AttributeValuesMatcher;
use CouponsPlus\app\coupon\attributes\abilities\AttributeMatcherInterface;

class VariationMatcher implements AttributeValuesMatcher
{

    /**
     * @var Collection
     */
    protected $attributeMatchers;

    public function __construct(Collection $attributeMatchers)
    {
        $this->attributeMatchers = $attributeMatchers;
    }

    /**
     * ALL MATCHERS SHOULD MATCH AT LEAST ONCE.
     *
     * This is the equivalent of an 'AND' comparison.
     *
     * Eg: VariationMatcher: [color:red AND size:small]
     *
     * If you want 'OR', simply create two instances of this class:
     *
     * Eg: -VariationMatcher1: [color:red]
     *     -VariationMatcher2: [size:small]
     *
     * @param Collection $attributesValues all the attribute values for a product (eg: [color:red, size:small])
     */
    public function matches(Collection $attributesValues) : bool
    {
        /** @var AttributeMatcherInterface $attributeMatcher */
        foreach ($this->attributeMatchers->asArray() as $attributeMatcher) {
            $matched = $attributesValues->find(
                function (AttributeValueData $attributeValueData) use ($attributeMatcher) {
                    return $attributeMatcher->matches($attributeValueData);
                }
            );
            if (!$matched) {
                return false;
            }
        }

        return true;
    }
}