<?php

namespace EdgeBox\SyncCore\V2\Syndication;

use EdgeBox\SyncCore\Interfaces\Syndication\IEntityReference;
use EdgeBox\SyncCore\V2\Raw\Model\RemoteEntityDependency;
use EdgeBox\SyncCore\V2\Raw\Model\RemoteEntityEmbed;
use EdgeBox\SyncCore\V2\Raw\Model\RemoteEntityEmbedDraft;
use EdgeBox\SyncCore\V2\Raw\Model\RemoteEntityEmbedRootDraft;
use EdgeBox\SyncCore\V2\Raw\Model\RemoteEntityRootEmbed;
use EdgeBox\SyncCore\V2\SyncCore;

class PullOperationEmbed implements IEntityReference
{
    /**
     * @var SyncCore
     */
    protected $core;

    /**
     * @var RemoteEntityDependency
     */
    protected $dto;

    /**
     * @var PullOperation
     */
    protected $pullOperation;

    /**
     * @var null|RemoteEntityEmbed|RemoteEntityEmbedDraft|RemoteEntityEmbedRootDraft|RemoteEntityRootEmbed
     */
    protected $embed;

    /**
     * @var null|int
     */
    protected $embedIndex;

    /**
     * constructor.
     *
     * @param null|mixed $embed
     */
    public function __construct(SyncCore $core, RemoteEntityDependency $dto, PullOperation $pullOperation, ?int $embedIndex, $embed = null)
    {
        $this->core = $core;
        $this->dto = $dto;
        $this->pullOperation = $pullOperation;
        $this->embed = $embed;
        $this->embedIndex = $embedIndex;
    }

    public function getDetails()
    {
        /**
         * @var null|array $details
         */
        $details = $this->dto->getReferenceDetails();

        if (!$details) {
            return [];
        }

        // Turn objects into arrays.
        return json_decode(json_encode($details), true);
    }

    public function getId()
    {
        return $this->dto->getRemoteUniqueId();
    }

    public function getUuid()
    {
        return $this->dto->getRemoteUuid();
    }

    public function getType()
    {
        return $this->dto->getEntityTypeNamespaceMachineName();
    }

    public function getBundle()
    {
        return $this->dto->getEntityTypeMachineName();
    }

    public function getVersion()
    {
        return $this->dto->getEntityTypeVersion();
    }

    public function getName()
    {
        return $this->dto->getName();
    }

    public function getPoolIds()
    {
        return $this->dto->getPoolMachineNames();
    }

    public function isEmbedded()
    {
        return (bool) $this->embed;
    }

    public function getEmbeddedEntity()
    {
        $this->pullOperation->embedProcessed($this->embedIndex);

        return new PullOperation(
            $this->core,
            $this->embed,
            false,
            $this->pullOperation
        );
    }
}
