<?php
declare(strict_types=1);

namespace FiloBlu\Refilo\Plugins\Model\Category;

use Exception;
use Magento\Framework\Serialize\SerializerInterface;

/**
 * @class AdaptEmotionalData
 * @package FiloBlu\Refilo\Plugins\Model\Category
 */
class AdaptEmotionalData
{

    /** @var string  */
    const EMOTIONAL_PRODUCTS_KEY = 'emotional_products';

    /**
     * @var SerializerInterface
     */
    private $serializer;

    /**
     * @param SerializerInterface $serializer
     */
    public function __construct(
        SerializerInterface $serializer
    ) {

        $this->serializer = $serializer;
    }

    /**
     * @param $subject
     * @param $result
     * @return array
     * @see \Magento\Catalog\Model\Category\DataProvider::getData
     */
    public function afterGetData($subject, $result)
    {
        if ($subject->getName() !== 'category_form_data_source') {
            return $result;
        }

        foreach ($result as $key => $categoryData) {
            if (!isset($categoryData[self::EMOTIONAL_PRODUCTS_KEY])) {
                continue;
            }

            try {
                $emotionalProduct = $this->serializer->unserialize($categoryData[self::EMOTIONAL_PRODUCTS_KEY]);

                $result[$key][self::EMOTIONAL_PRODUCTS_KEY] = $emotionalProduct;
            } catch (Exception $e) {
            }
        }

        return $result;
    }
}
