<?php
namespace Backend\BaseBundle\Service;

use JMS\DiExtraBundle\Annotation\Service;
use JMS\DiExtraBundle\Annotation\Tag;
use JMS\DiExtraBundle\Annotation\Inject;
use JMS\DiExtraBundle\Annotation\InjectParams;
use Assetic\Factory\Resource\ResourceInterface;
use Symfony\Bundle\AsseticBundle\Factory\Loader\ConfigurationLoader;
use Symfony\Component\HttpKernel\Bundle\Bundle;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Component\Yaml\Parser;

/**
 * @Service(public=false)
 * @Tag("assetic.formula_loader", attributes = {"alias": "config"})
 */
class AsseticLoader extends ConfigurationLoader
{

    /**
     * @var KernelInterface
     */
    protected $kernel;

    /**
     * @InjectParams()
     */
    public function injectKernel(KernelInterface $kernel)
    {
        $this->kernel = $kernel;
    }

    public function load(ResourceInterface $resource)
    {
        $resourceArray = parent::load($resource);
        $config = $this->loadConfig();
        $resourceArray['backend_base_js'][0] = $this->sortResourceArray(array_merge($resourceArray['backend_base_js'][0], $config['js']));
        $resourceArray['backend_base_css'][0] = $this->sortResourceArray(array_merge($resourceArray['backend_base_css'][0], $config['css']));
        return $resourceArray;
    }

    protected function sortResourceArray($array)
    {
        $resultArray = array();
        $priorityArray = array('high', 'medium', 'low');
        foreach($priorityArray as $priority){
            if(!isset($array[$priority])){
                continue;
            }
            $resultArray = array_merge($resultArray, $array[$priority]);
        }
        return $resultArray;
    }

    protected function loadConfig()
    {
        $config = array(
            'js' => array(),
            'css' => array(),
        );
        foreach($this->kernel->getBundles() as $bundle){
            if(!($bundleConfig = $this->loadBundleConfig($bundle))){
                continue;
            }
            if(isset($bundleConfig['backend']['js'])){
                $config['js'] = array_merge_recursive($config['js'], $bundleConfig['backend']['js']);
            }
            if(isset($bundleConfig['backend']['css'])){
                $config['css'] = array_merge_recursive($config['css'], $bundleConfig['backend']['css']);
            }
        }
        return $config;
    }

    protected function loadBundleConfig(Bundle $bundle)
    {
        if(!($path = realpath($bundle->getPath()."/Resources/config/assets/partial.yml")) || !file_exists($path)){
            return null;
        }
        $parser =  new Parser();
        $config = $parser->parse(file_get_contents($path));
        return $config;
    }
}