<?php

namespace Comitium5\DesignerBundle\ValueObjects;

/**
 * Class PageMessageObject
 *
 * @author Oscar Jimenez <oscarjg19.developer@gmail.com>
 * @package Comitium5\DesignerBundle\ValueObjects
 */
class PageMessageObject
{
    /**
     * @var int
     */
    protected $id;

    /**
     * @var bool
     */
    protected $isPublished;

    /**
     * @var string
     */
    protected $event;

    /**
     * PageMessageObject constructor.
     *
     * @param string $messageBody
     *
     * @throws \Exception
     */
    public function __construct(string $messageBody)
    {
        $data = json_decode($messageBody, true);

        $this->validate($data);

        $this->id          = (int) $data["data"]["attributes"]["id"];
        $this->isPublished = (bool) $data["data"]["attributes"]["is_published"];
        $this->event       = (string) $data["data"]["event"];
    }

    public function getId(): int
    {
        return $this->id;
    }

    /**
     * @return bool
     */
    public function isPublished(): bool
    {
        return $this->isPublished;
    }

    /**
     * @return string
     */
    public function getEvent(): string
    {
        return $this->event;
    }

    /**
     * @param array $data
     *
     * @throws \Exception
     */
    protected function validate(array $data): void
    {
        if (!isset($data["data"]["attributes"])) {
            throw new \Exception('Invalid message body. Attributes key expected');
        }

        if (!isset($data["data"]["event"])) {
            throw new \Exception('Invalid message body. Event key expected');
        }
    }
}