<?php

namespace CouponsPlus\App\Coupon\Attributes\Factories;

use WP_Term;
use WC_Product_Attribute;
use CouponsPlus\Original\Collections\Collection;
use CouponsPlus\App\Coupon\Attributes\VariationMatcher;
use CouponsPlus\App\Coupon\Attributes\AttributeMatcher;
use CouponsPlus\App\Coupon\Attributes\AttributeToMatch;
use CouponsPlus\App\Coupon\Attributes\Data\GlobalAttributeData;

class VariationMatcherFactory
{
    /**
     * @var AttributeMatcherFactory
     */
    protected $attributeMatcherFactory;

    public function __construct(AttributeMatcherFactory $attributeMatcherFactory)
    {
        $this->attributeMatcherFactory = $attributeMatcherFactory;
    }

    /**
     * The format is:
     * [
     *      {type: 'allowed', attribute: {id: 12, values: [34, 25]}},
     *      {type: 'any', attribute: {id: 20, values: []}}
     * ]
     * @param string|object|array $json
     * @return VariationMatcher
     */
    public function create($json) : VariationMatcher
    {
        $attributesToMatchRawData = $json;

        if (is_string($json)) {
            $attributesToMatchRawData = json_decode($json);
        }

        return new VariationMatcher(
            Collection::create($attributesToMatchRawData)->map(function ($attributeToMatchRawData) : AttributeMatcher {
                return $this->attributeMatcherFactory->create(
                    $attributeToMatchRawData->type,
                    $attributeToMatchRawData->attribute->id,
                    $attributeToMatchRawData->attribute->values
                );
            })
        );
    }
}