<?php

namespace KupShop\I18nBundle\EventListener;

use KupShop\AdminBundle\Util\ActivityLog;
use KupShop\I18nBundle\Util\AutomaticReviewsTranslation;
use KupShop\KupShopBundle\Event\CronEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class CronListener implements EventSubscriberInterface
{
    /**
     * @var AutomaticReviewsTranslation
     */
    protected $automaticReviewsTranslation;

    public function __construct(AutomaticReviewsTranslation $automaticReviewsTranslation)
    {
        $this->automaticReviewsTranslation = $automaticReviewsTranslation;
    }

    public static function getSubscribedEvents()
    {
        return [
            CronEvent::RUN_EXPENSIVE => [
                ['generateTranslations', 500],
            ],
        ];
    }

    public function generateTranslations()
    {
        $dbcfg = \Settings::getDefault();
        $translateCharacters = [];

        foreach ($dbcfg->automatic_translate['languages'] ?? [] as $lang) {
            $translateCharacters[$lang] = $this->automaticReviewsTranslation->translateReviews($lang);
        }

        if (!empty($translateCharacters)) {
            $log = [];
            foreach ($translateCharacters as $key => $result) {
                if ($result['characters'] > 0) {
                    $log[$key] = 'Přeloženo  hodnocení: '.array_sum($result['add_reviews']).' Celkem znaků: '.$result['characters'];
                }
            }
            if ($log) {
                addActivityLog(ActivityLog::SEVERITY_SUCCESS,
                    ActivityLog::TYPE_SYNC,
                    'Překlady hodnocení produktů dokončeny',
                    $log);
            }
        }
    }
}
