<?php

namespace External\SprintBundle\Controller;

use External\MSSQLBundle\Util\SynchronizerLocator;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Symfony\Component\Routing\Annotation\Route;

class HeliosController extends AbstractController
{
    /**
     * @Route("/_helios/{type}/")
     */
    public function syncAction(Request $request, SynchronizerLocator $locator, $type = null): StreamedResponse
    {
        return new StreamedResponse(function () use ($type, $locator, $request) {
            // Clear output buffering
            while (ob_get_level()) {
                ob_end_clean();
            }

            sqlGetConnection()->getConfiguration()->setSQLLogger();

            $synchronizer = $locator->getServiceByType($type);
            if ($request->get('fullSync')) {
                $synchronizer->setFullSync(true);
            }
            $transactional = $request->get('transactional') ?: false;
            $synchronizer->sync($transactional);

            $this->log("Synchronizace {$type} dokončena");
        });
    }

    /**
     * @Route("/_helios_product_without_image/")
     */
    public function syncProductAction(Request $request, SynchronizerLocator $locator, $type = null): StreamedResponse
    {
        return new StreamedResponse(function () use ($type, $locator, $request) {
            // Clear output buffering
            while (ob_get_level()) {
                ob_end_clean();
            }

            sqlGetConnection()->getConfiguration()->setSQLLogger();

            $synchronizer = $locator->getServiceByType('product');
            if ($request->get('fullSync')) {
                $synchronizer->setFullSync(true);
            }
            $synchronizer::$syncImage = false;
            $synchronizer->sync(false);

            $this->log("Synchronizace {$type} dokončena");
        });
    }

    /**
     * @Route("/_helios_full_product_with_image/")
     */
    public function syncFullProductAction(Request $request, SynchronizerLocator $locator, $type = null): StreamedResponse
    {
        return new StreamedResponse(function () use ($type, $locator) {
            // Clear output buffering
            while (ob_get_level()) {
                ob_end_clean();
            }

            sqlGetConnection()->getConfiguration()->setSQLLogger();

            $synchronizer = $locator->getServiceByType('product');
            $synchronizer->setFullSync(true);
            $synchronizer->sync(false);

            $this->log("Synchronizace {$type} dokončena");
        });
    }

    private function log(string $text): void
    {
        echo '['.date('Y-m-d H:i:s').'] '.$text.'<br>';
        flush();
    }
}
