<?php
/**
 * Copyright 2020 Adobe
 * All Rights Reserved.
 *
 * NOTICE: Adobe permits you to use, modify, and distribute this file in
 * accordance with the terms of the Adobe license agreement accompanying
 * it.
 */
declare(strict_types=1);

namespace Magento\Mray\Index\Data;

use Magento\Mray\Index\Collection\Dictionary;
use function array_filter;
use function json_decode;
use function json_encode;
use function substr;

abstract class DataTransferObject
{
    /**
     * @param mixed $data
     */
    abstract protected function __construct($data);

    /**
     * @param array $packed
     * @param Dictionary $dict
     * @return array
     */
    abstract protected static function unpackData(array $packed, Dictionary $dict): array;

    /**
     * @param Dictionary $dict
     * @return array
     */
    abstract protected function packData(Dictionary $dict): array;

    /**
     * @param string $data
     * @param Dictionary $dict
     * @return static
     */
    final public static function unpack(string $data, Dictionary $dict): self
    {
        return new static(static::unpackData(self::unstringify($data), $dict));
    }

    /**
     * @param Dictionary $dict
     * @return string
     */
    final public function pack(Dictionary $dict)
    {
        return self::stringify($this->packData($dict));
    }

    /**
     * @param array $data
     * @return string
     */
    final protected static function stringify(array $data): string
    {
        $data = (object)array_filter($data, function ($v) {
            return $v !== null;
        });
        return substr(json_encode($data), 1, -1);
    }

    /**
     * @param string $data
     * @return array
     */
    final protected static function unstringify(string $data): array
    {
        return json_decode('{' . $data . '}', true);
    }
}
