<?php

declare(strict_types=1);

namespace KupShop\CDNBundle\Resources\script;

use KupShop\AdminBundle\Util\Script\Script;
use Query\Operator;

class CDNRefreshVideoThumbnailScript extends Script
{
    protected static $name = '[CDN] Refresh video thumbnails';
    protected static $defaultParameters = [
        'photoIds' => null,
    ];

    protected function run(array $arguments)
    {
        $qb = sqlQueryBuilder()
            ->select('ph.*, v.id_cdn as id_video')
            ->from('photos', 'ph')
            ->join('ph', 'videos', 'v', 'ph.id = v.id_photo');

        if ($arguments['photoIds'] ?? []) {
            $qb->andWhere(Operator::inIntArray($arguments['photoIds'], 'ph.id'));
        }

        foreach ($qb->execute() as $photo) {
            if (!$this->refreshVideoThumbnail($photo)) {
                $this->log('Unable to refresh video thumbnail: '.$photo['id']);
                continue;
            }

            $this->log('Refreshed video thumbnail: '.$photo['id']);
        }
    }

    private function refreshVideoThumbnail(array $photo): bool
    {
        $img = new \Photos('none');
        $img->newImage($photo['id']);

        if ($result = $img->refreshVideoThumbnail($photo)) {
            $img->updateDateUpdated();
        }

        return $result;
    }
}

return CDNRefreshVideoThumbnailScript::class;
