<?php

namespace Velis\Queue;

use ArrayAccess;
use Resque;
use Velis\App;

/**
 * @author Jan Małysiak <jan.malysiak@velis.pl>
 * @property array $args
 */
abstract class AbstractJob implements JobInterface
{
    /**
     * @var string
     */
    private $instanceAcro;

    /**
     * @var array|ArrayAccess
     */
    private $params;

    /**
     * AbstractJob constructor.
     * @todo inject instanceAcro as a constructor parameter
     */
    public function __construct()
    {
        $this->instanceAcro = App::$config->settings->instanceAcro;
    }

    /**
     * {@inheritDoc}
     */
    public function addToQueue(QueueInterface $queue): void
    {
        $queueName = $this->getQueueName();
        if ($this->instanceAcro) {
            $queueName .= '-' . $this->instanceAcro;
        }

        $queue->enqueue($queueName, static::class, $this->params);
    }

    /**
     * Return queue name
     * @return string
     */
    abstract protected function getQueueName();

    /**
     * Set parameters
     * @param array|ArrayAccess $params
     */
    public function setParams($params)
    {
        $this->params = $params;
    }

    /**
     * {@inheritDoc}
     */
    public function setUp(): void
    {
    }

    /**
     * {@inheritDoc}
     */
    public function tearDown(): void
    {
    }

    protected function isQueueEmpty(bool $instanceAcro = true): bool
    {
        $queue = $this->getQueueName();
        if ($instanceAcro) {
            $queue .= '-' . $this->instanceAcro;
        }

        return Resque::size($queue) === 0;
    }
}
