<?php

namespace KupShop\ContentBundle\EventListener;

use KupShop\AdminBundle\Util\ActivityLog;
use KupShop\ContentBundle\Util\InstagramUtil;
use KupShop\KupShopBundle\Context\LanguageContext;
use KupShop\KupShopBundle\Event\CronEvent;
use KupShop\KupShopBundle\Util\Contexts;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class CronListener implements EventSubscriberInterface
{
    /** @required  */
    public InstagramUtil $instagramUtil;

    public static function getSubscribedEvents()
    {
        return [
            CronEvent::RUN_NORMAL => [
                ['updateInstagram', 200],
            ],
        ];
    }

    public function updateInstagram()
    {
        if (\Settings::getDefault()->instagram['api'] ?? '') {
            foreach (Contexts::get(LanguageContext::class)->getSupported() as $lang => $tmp) {
                try {
                    $data = $this->instagramUtil->updateFeed($lang);

                    if ($data) {
                        $count = count($data['data']);
                        addActivityLog(ActivityLog::SEVERITY_SUCCESS, ActivityLog::TYPE_COMMUNICATION,
                            "Úspěšná aktualizace Instagram feedu pro jazyk {$lang}. Staženo {$count} položek.");
                    }
                } catch (\InvalidArgumentException $exception) {
                    addActivityLog(ActivityLog::SEVERITY_ERROR, ActivityLog::TYPE_COMMUNICATION,
                        "Instagram vrátil chybu při generování {$lang} feedu: {$exception->getMessage()}");
                }
            }
        }
    }
}
