<?php

namespace CouponsPlus\App\Conditions;

use CouponsPlus\App\Offers\OffersRegistrator;
use CouponsPlus\Original\Collections\JSONMapper;
use CouponsPlus\Original\Collections\MappedObject;

/**
 * This is a factory and this could be implemented as a function,
 * but oh well...
 */
class Card
{
    /**
     * Will create options from registered: offers, conditions or filters
     *
     * $cardType is offer, filter or condition
     * 
     */
    public static function createOptions(string $cardType, $data) : MappedObject
    {
        switch($cardType) {
            case 'offer':
                (object) $RegisteredComponentsClass = OffersRegistrator::class;
            break;
            case 'filter':
                (object) $RegisteredComponentsClass = FiltersRegistrator::class;
            break;
            case 'condition':
                (object) $RegisteredComponentsClass = ConditionsRegistrator::class;
            break;
        }
        (string) $type = is_string($data)? json_decode($data)->type : $data->type;

        (string) $Component = $RegisteredComponentsClass::get()->all()->get($type);

        (object) $offerJsonMapper = new JSONMapper($Component::getOptions()->asArray());
        
        (object) $mappedOptions = $offerJsonMapper->smartMap($data->options);

        //smartmap() may not return a mapped object
        if ($mappedOptions instanceof MappedObject) {
            return $mappedOptions;
        }

        return new MappedObject([]);
    }
}