<?php

namespace External\VarioBundle\Util;

use External\VarioBundle\Synchronizers\ProductSynchronizer;
use External\VarioBundle\Synchronizers\SupplySynchronizer;
use External\VarioBundle\Synchronizers\TranslationSynchronizer;
use Query\Operator;

class VarioDelayedUpdate
{
    public const ITEMS_MAX = 1000;

    private $varioHelper;

    public function __construct(VarioHelper $varioHelper)
    {
        $this->varioHelper = $varioHelper;
    }

    public function processDelayedUpdate(int $maxItems = self::ITEMS_MAX): int
    {
        $qb = sqlQueryBuilder()
            ->select('*')
            ->from('vario_delayed_update')
            ->setMaxResults($maxItems);

        $count = 0;
        foreach ($qb->execute() as $item) {
            try {
                $method = 'process'.ucfirst($item['type']);
                if (method_exists($this, $method)) {
                    $this->{$method}($item['id_vario']);
                }

                sqlQueryBuilder()
                    ->delete('vario_delayed_update')
                    ->where(Operator::equals($item))
                    ->execute();

                $count++;
            } catch (\Throwable $e) {
                sqlQueryBuilder()
                    ->delete('vario_delayed_update')
                    ->where(Operator::equals($item))
                    ->execute();

                $count++;
            }
        }

        $this->postprocess();

        return $count;
    }

    public function processOtAvailableSupply(string $varioId): void
    {
        $this->varioHelper->doForceSync($varioId, SupplySynchronizer::getType());
    }

    public function processOtProduct(string $varioId): void
    {
        $this->varioHelper->doForceSync($varioId, ProductSynchronizer::getType());
    }

    public function processOtCustomer(string $varioId): void
    {
        $this->varioHelper->doForceSync($varioId, 'otCustomer');
    }

    public function processOtTranslation(string $varioId): void
    {
        $this->varioHelper->doForceSync($varioId, TranslationSynchronizer::getType());
    }

    protected function postprocess(): void
    {
        $this->varioHelper->updateProductsPriceToMinFromVariations();
    }
}
