<?php

namespace App\Service;

use App\Event\StatCheckedEvent;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;

class StatsProcessor
{
    private $checkers;
    private $domain;
    private $domainId;
    private $dispatcher;

    public function __construct(EventDispatcherInterface $dispatcher)
    {
        $this->dispatcher = $dispatcher;
    }

    public function addChecker(StatCheckerInterface $checker)
    {
        $this->checkers[] = $checker;
    }

    public function getCheckers()
    {
        return $this->checkers;
    }

    public function process()
    {
        if (is_array($this->getCheckers())) {
            array_map(function (StatCheckerInterface $checker) {
                $response = $checker->check($this->getDomain());

                $this->dispatchEvent($response);
            }, $this->getCheckers());
        }
    }

    /**
     * @return mixed
     */
    public function getDomain()
    {
        return $this->domain;
    }

    private function dispatchEvent(StatResponse $response)
    {
        $event = new StatCheckedEvent($response, $this->domainId);
        $this->dispatcher->dispatch('event.stat_checked', $event);
    }

    /**
     * @param mixed $domain
     */
    public function setDomain($domain): void
    {
        $this->domain = $domain;
    }

    /**
     * @param int $domainId
     */
    public function setDomainId(int $domainId): void
    {
        $this->domainId = $domainId;
    }
}
