<?php
namespace Newland\NeosCommon\Domain\Model;

use function Safe\json_encode;

class Topic implements \Serializable
{
    /** @var string */
    private $title;

    /** @var string */
    private $type;

    /** @var string */
    private $identifier;

    /** @var mixed|null */
    private $value;

    public function __construct(string $type, string $identifier, string $title, string $value = null)
    {
        $this->type = $type;
        $this->identifier = $identifier;
        $this->title = $title;
        $this->value = $value;
    }

    public function getTitle(): string
    {
        return $this->title;
    }

    public function getIdentifier(): string
    {
        return $this->identifier;
    }

    public function getCombinedIdentifier(): string
    {
        $identifier = $this->type . ':' . $this->identifier;
        if ($this->value) {
            $identifier .= ':' . $this->value;
        }
        return $identifier;
    }

    public function getType(): string
    {
        return $this->type;
    }

    public function getValue(): string
    {
        return $this->value;
    }
    public function getValueOrIdentifier(): string
    {
        return $this->value ?? $this->identifier;
    }

    public function serialize(): string
    {
        return json_encode(
            [
                'title' => $this->getTitle(),
                'type' => $this->getType(),
                'identifier' => $this->getIdentifier(),
                'value' => $this->getValue(),
            ]
        );
    }

    /** @param string $serialized */
    public function unserialize($serialized): void
    {
        $properties = json_decode($serialized, true);
        $this->title = $properties['title'];
        $this->type = $properties['type'];
        $this->identifier = $properties['identifier'];
        $this->value = $properties['value'];
    }
}
