<?php

namespace AppBundle\Service\Queue;

use AppBundle\Model\Queue\QueuedCommand;
use Enqueue\Client\ProducerInterface;

class QueuedCommandHandler
{
    /**
     * @var ProducerInterface
     */
    protected $producer;

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

    /**
     * @param ProducerInterface $producer
     * @param string $env
     */
    public function __construct(ProducerInterface $producer, $env)
    {
        $this->producer = $producer;
        $this->env = $env;
    }

    public function handle(QueuedCommand $command): void
    {
        $argumentString = $this->createArgumentString($command->getParameters());
        $fullCommand = sprintf('%s %s', $command->getName(), $argumentString);
        $this->producer->sendCommand('run_command', $fullCommand);
    }

    public function handleString(string $fullCommand): void
    {
        $this->producer->sendCommand('run_command', $fullCommand);
    }

    private function createArgumentString(array $arguments)
    {
        $optionList = [];
        foreach ($arguments as $key => $value) {
            if (!is_int($key)) {
                $optionList[] = sprintf('--%s=%s', $key, $value);
                continue;
            }
            $optionList[] = sprintf('%s', $value);
        }
        $optionList[] = sprintf('--env=%s', $this->env);

        return implode(' ', $optionList);
    }
}