<?php

namespace EdgeBox\SyncCore\V2\Syndication;

use EdgeBox\SyncCore\Interfaces\IApplicationInterface;
use EdgeBox\SyncCore\Interfaces\Syndication\ITriggerPullSingle;
use EdgeBox\SyncCore\V2\Helper;
use EdgeBox\SyncCore\V2\Raw\Model\CreateTaskDto;
use EdgeBox\SyncCore\V2\Raw\Model\TaskEntity;
use EdgeBox\SyncCore\V2\SyncCore;

class TriggerPullSingle implements ITriggerPullSingle
{
    /**
     * @var SyncCore
     */
    protected $core;

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

    /**
     * The Syndication Entity, set when running ->execute().
     *
     * @var TaskEntity
     */
    protected $syndication;

    /**
     * TriggerPullSingle constructor.
     */
    public function __construct(SyncCore $core, string $namespace_machine_name, string $machine_name, string $shared_entity_id, string $flow_id)
    {
        $this->core = $core;

        $this->dto = new CreateTaskDto();
        $this->dto->setFlowMachineName($flow_id);
        $this->dto->setPoolMachineNames([]);
        $this->dto->setEntityTypeNamespaceMachineName($namespace_machine_name);
        $this->dto->setEntityTypeMachineName($machine_name);

        if (Helper::isUuid($shared_entity_id)) {
            $this->dto->setRemoteUuid($shared_entity_id);
        } else {
            $this->dto->setRemoteUniqueId($shared_entity_id);
        }
    }

    // TODO: Drupal: Support multiple pools.
    public function fromPool(string $pool_id)
    {
        $pools = $this->dto->getPoolMachineNames();
        $pools[] = $pool_id;
        $this->dto->setPoolMachineNames($pools);

        return $this;
    }

    public function manually(bool $set)
    {
        $this->dto->setManually($set);

        return $this;
    }

    public function asDependency(bool $set)
    {
        $this->dto->setAsDependency($set);

        return $this;
    }

    public function execute()
    {
        $request = $this->core->getClient()->syndicationControllerCreateRequest(createTaskDto: $this->dto);
        $this->syndication = $this->core->sendToSyncCoreAndExpect($request, TaskEntity::class, IApplicationInterface::SYNC_CORE_PERMISSIONS_CONTENT, false, SyncCore::PULL_RETRY_COUNT);

        return $this;
    }

    public function getPullDashboardSearchResultItem()
    {
        return null;
    }

    /**
     * @return null|string the update ID to query for the status
     */
    public function getId()
    {
        if ($this->syndication) {
            return $this->syndication->getId();
        }
    }
}
