<?php

namespace KupShop\KupShopBundle\Routing\Compiler;

use KupShop\KupShopBundle\Config;
use Symfony\Component\Routing\CompiledRoute;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCompiler;

class CampaignRouteCompiler extends RouteCompiler
{
    public static function compile(Route $route): CompiledRoute
    {
        if (isset($route->getRequirements()['campaign'])) {
            $requirements = $route->getRequirements();

            // reset requirements
            $route->setRequirements([]);

            $campaignRequirements = static::translateCampaigns($requirements['campaign']);
            if (empty($campaignRequirements)) {
                $route->setCondition('false');
                // unset campaign requirements if campaigns are not specified
                unset($requirements['campaign']);
            } else {
                $requirements['campaign'] = $campaignRequirements;
            }

            $route->addRequirements($requirements);
        }

        return parent::compile($route);
    }

    private static function translateCampaigns($parameter)
    {
        $campaigns = getCampaigns();

        $parameter = array_filter(explode('|', $parameter), function ($x) { return trim($x); });
        $values = [];
        foreach ($parameter as $value) {
            $key = static::getCampaignKeyByUrl($value);
            if ($key === null) {
                $values[] = $value;
            } else {
                $values[] = $campaigns[$key]['url'];
            }
        }

        return join('|', $values);
    }

    private static function getCampaignKeyByUrl($url)
    {
        $cfg = Config::get();

        foreach ($cfg['Products']['Flags'] as $key => $flag) {
            if (($flag['url'] ?? '') == $url) {
                return $key;
            }
        }

        return null;
    }
}
