<?php

namespace App\EventSubscriber;

use App\Entity\Domain\Stat;
use App\Entity\Domain\Stat\Check;
use App\Event\StatCheckedEvent;
use App\Service\Domain\Stat\CheckService;
use App\Service\Domain\StatService as DomainStatService;
use App\Service\DomainService;
use App\Service\StatService;

final class StatCheckedSubscriber
{
    private $domainService;
    private $checkService;
    /**
     * @var DomainStatService
     */
    private $domainStatService;
    /**
     * @var StatService
     */
    private $statService;

    public function __construct(DomainService $domainService, CheckService $checkService, DomainStatService $domainStatService, StatService $statService)
    {
        $this->domainService = $domainService;
        $this->checkService = $checkService;
        $this->domainStatService = $domainStatService;
        $this->statService = $statService;
    }

    public function onUpdate(StatCheckedEvent $event)
    {
        try {
            $domain = $this->domainService->getDomain($event->getDomainId());
        } catch (\Exception $e) {
            return null;
        }
        $stat = $domain->getStats()->filter(function ($stat) use ($event) {
            return $stat->getStat()->getSymbol() === $event->getSymbol();
        })->first();

        if (!$stat) {
            $statEntity = $this->statService->bySymbol($event->getSymbol());
            $domainStat = new Stat();
            $domainStat->setDomain($domain);
            $domainStat->setStat($statEntity);
            $stat = $this->domainStatService->save($domainStat);
        }

        if ($stat->getChecks()->count() > 0) {
            $latestCheck = $stat->getChecks()[0];
            $diff = $event->getValue() - $latestCheck->getValue();
        } else {
            $diff = $event->getValue();
        }

        $this->checkService->save((new Check())->setStat($stat)->setValue($event->getValue())->setDiff($diff));
    }
}
