<?php

namespace CouponsPlus\App\Coupon\Attributes\Factories;

use WP_Term;
use CouponsPlus\App\Coupon\Attributes\Abilities\AttributeData;
use CouponsPlus\app\coupon\attributes\abilities\AttributeValueData;
use CouponsPlus\App\Coupon\Attributes\Data\GlobalAttributeValueData;
use CouponsPlus\App\Coupon\Attributes\Abilities\AttributeValueDataFactory;

/**
 * This class should use 4 different classes but ain't nobody got time for dat rn
 */
class GlobalAttributeValueDataFactory implements AttributeValueDataFactory
{
    /**
     * @var AttributeData
     */
    protected $attributeData;

    public function setAttributeData(AttributeData $attributeData)
    {
        $this->attributeData = $attributeData;
    }

    /**
     * @param string|int|WP_Term|AttributeValueData $value
     * @throws \Exception
     */
    public function create($value): AttributeValueData
    {
        switch (true) {
            case $value instanceof AttributeValueData:
                return $value;
            case $value instanceof WP_Term:
                return $this->createFromWPTerm($value);
            case is_int($value):
                return $this->createFromId($value);
            case is_string($value):
                return $this->createFromSlug($value);
        }
    }

    /**
     * @param WP_Term $value
     * @return GlobalAttributeValueData
     */
    public function createFromWPTerm(WP_Term $value): GlobalAttributeValueData
    {
        return new GlobalAttributeValueData($value, $this->attributeData);
    }

    /**
     * @param string $value
     * @return GlobalAttributeValueData
     */
    public function createFromSlug(string $value): GlobalAttributeValueData
    {
        return $this->createFromWPTerm(get_term_by(
            'slug',
            $value,
            $this->attributeData->getKey()->ensureLeft('pa_')->get()
        ));
    }

    /**
     * @param int $value
     * @return GlobalAttributeValueData
     */
    public function createFromId(int $value): GlobalAttributeValueData
    {
        $term = get_term_by(
            'id',
            $value,
            $this->attributeData->getKey()->ensureLeft('pa_')->get()
        );

        return $this->createFromWPTerm($term);
    }
}