<?php

namespace Daylight\Core\Modules\Admin\Registries;

use Daylight\Core\Modules\Admin\Entities\Widget;
use Illuminate\Support\Collection;

class WidgetRegistry
{
    protected Collection $widgets;

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

    public static function addWidget(Widget $widget): self
    {
        return app(self::class)->register($widget);
    }

    public function register(array|Collection|Widget $widgets): self
    {
        if ($widgets instanceof Widget) {
            $widgets = [$widgets];
        }

        if (is_array($widgets)) {
            $widgets = collect($widgets);
        }

        $this->widgets = $this->widgets->merge($widgets);

        return $this;
    }

    public function all(): Collection
    {
        return $this->widgets->filter(function (Widget $widget) {
            return auth()->user()->can($widget->getPermission());
        })->sortBy('order')->values();
    }
}
