<?php

declare(strict_types=1);

namespace FiloBlu\ActiveCampaign\Helper;

use InvalidArgumentException;
use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Framework\App\Helper\Context;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\Serialize\SerializerInterface;

/**
 * Class SerializerHelper
 * @package FiloBlu\ActiveCampaign\Helper
 */
class SerializerHelper extends AbstractHelper
{
    /**
     * @var SerializerInterface|null
     */
    public $magentoSerializer;

    /**
     * Data constructor.
     * @param Context $context
     */
    public function __construct(
        Context $context
    ) {
        $this->magentoSerializer = null;
        if (interface_exists(SerializerInterface::class)) {
            $objectManager = ObjectManager::getInstance();
            $serializer = $objectManager->create(SerializerInterface::class);
            $this->magentoSerializer = $serializer;
        }

        parent::__construct($context);
    }

    /**
     * @param $data
     * @return string
     */
    public function serialize($data)
    {
        if (isset($this->magentoSerializer)) {
            return $this->magentoSerializer->serialize($data);
        }

        $result = json_encode($data);
        if ($result === false) {
            return serialize($data);
        }

        return $result;
    }

    /**
     * @param $string
     * @return mixed
     */
    public function unserialize($string)
    {
        if ($string === false || $string === null || $string === '') {
            throw new InvalidArgumentException('Unable to unserialize value.');
        }

        if (isset($this->magentoSerializer)) {
            return $this->magentoSerializer->unserialize($string);
        }

        $result = json_decode($string, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            throw new InvalidArgumentException('Unable to unserialize value. Error: ' . json_last_error_msg());
        }

        return $result;
    }
}
