<?php

namespace Daylight\Core\Modules\PageBuilder\Registries;

use Daylight\Core\Modules\PageBuilder\Entities\Component;
use Illuminate\Support\Collection;

class ComponentRegistry
{
    protected Collection $components;

    public function __construct()
    {
        $this->components = collect();
    }

    public function register(Component $component): self
    {
        $this->components->put($component->type(), $component);

        return $this;
    }

    public static function addComponent(Component $component): self
    {
        return app(ComponentRegistry::class)->register($component);
    }

    public static function addComponents(array|Collection $components)
    {
        if (is_array($components)) {
            $components = collect($components);
        }

        return $components->each(fn (Component $component) => self::addComponent($component));
    }

    public function getDefinition(string $type): ?Component
    {
        return $this->components->get($type);
    }

    public function all(): Collection
    {
        return $this->components;
    }

    public function availableFor(?string $object = null)
    {
        return self::all()
            ->map(fn ($component) => $component::getInstance())
            ->filter(function (Component $component) use ($object) {
                if (is_null($object)) {
                    return true;
                }

                if ($component->disabledFor()->isNotEmpty()) {
                    return $component->disabledFor()->doesntContain($object);
                }

                if ($component->availableFor()->isEmpty()) {
                    return true;
                }

                return $component->availableFor()->contains($object);
            });
    }
}
