<?php

namespace KupShop\KupShopBundle\Routing;

use KupShop\KupShopBundle\Util\Compat\ServiceContainer;
use KupShop\KupShopBundle\Util\StringUtil;
use KupShop\KupShopBundle\Util\System\BundleFinder;
use KupShop\KupShopBundle\Util\System\PathFinder;
use Symfony\Component\Config\Exception\FileLocatorFileNotFoundException;
use Symfony\Component\Config\Loader\Loader;
use Symfony\Component\Routing\RouteCollection;

class SubmoduleLoader extends Loader
{
    public function load($resource, $type = null)
    {
        $collection = new RouteCollection();

        $bundleFinder = new BundleFinder(new PathFinder());

        // Load routing.yml from app/config/
        if (!isFunctionalTests()) {
            try {
                $this->loadRouting('./app/config/routing.yml', $collection);
            } catch (FileLocatorFileNotFoundException $e) {
                // skip if not exists
            }
        }

        // Load all routing.yml files from all loaded KupShop bundles
        $loadBundlesRoutingFile = function ($file) use ($bundleFinder, &$collection) {
            foreach ($bundleFinder->getBundlesResource('Resources/config/'.$file) as $bundle => $path) {
                // Avoid recursion
                if ($bundle == 'KupShopBundle') {
                    continue;
                }

                $this->loadRouting($path, $collection);
            }
        };

        $loadBundlesRoutingFile('routing.yml');

        $env = ServiceContainer::getKernel()->getEnvironment();
        $loadBundlesRoutingFile("routing_{$env}.yml");

        if (findModule(\Modules::COMPONENTS)) {
            $loadBundlesRoutingFile('routing-components.yml');
        }

        return $collection;
    }

    /**
     * @param RouteCollection $collection
     *
     * @throws \Symfony\Component\Config\Exception\FileLoaderLoadException
     */
    public function loadRouting($path, &$collection)
    {
        // Load routing.yml
        try {
            $this->resolve($path, 'yaml')->getLocator();
            $importedRoutes = $this->import($path, 'yaml');
            $collection->addCollection($importedRoutes);
        } catch (\InvalidArgumentException $e) {
            // Ignore if autorouting.yml does not exists
            // HACK: Jak sakra rozlisit jestli neexistuje, nebo neni validni? Musim takhle hnusne podle textu :-( Oboji je to InvalidArgumentException
            if (!StringUtil::startsWith($e->getMessage(), 'Unable to find file')) {
                throw $e;
            }
        }
    }

    public function supports($resource, $type = null)
    {
        return 'kupshop' === $type;
    }
}
