<?php

namespace AutoAdmin\Bundle\Content\Configuration;

use Symfony\Component\PropertyAccess\PropertyAccessor;

class ConfigManipulator
{
    /**
     * @var array
     */
    private $config;
    private ?PropertyAccessor $accessor;

    public function __construct(array $config)
    {
        $this->config = $config;
        $this->accessor = new PropertyAccessor();
    }

    public function getConfig()
    {
        return $this->config;
    }

    public function get($path)
    {
        $path = '['.str_replace('.', '][', $path).']';

        return $this->accessor->getValue($this->config, $path);
    }

    protected function set($path, $value)
    {
        $path = '['.str_replace('.', '][', $path).']';

        $this->accessor->setValue($this->config, $path, $value);
    }

    public function addAsset(string $type, string $url, bool $fromTop = false)
    {
        $val = $this->get('assets.'.$type);

        if (!is_array($val)) {
            $val = [];
        }

        if ($fromTop) {
            array_unshift($val, $url);
        } else {
            array_push($val, $url);
        }

        $this->set('content.assets.'.$type, $val);
    }
}
