<?php

namespace kernel;

class Assets
{
    protected array $jsHeader = [];
    protected array $jsBody = [];

    protected array $collectorJs = [];

    protected array $css = [];

    protected array $collectorCss = [];

    protected string $resourceURI = "/resource";

    public function __construct(string $resourceURI)
    {
        $this->setResourceURI($resourceURI);
        $this->createCSS();
        $this->createJS();
    }

    protected function createCSS(){}
    protected function createJS(){}

    public function setResourceURI(string $resourceURI): void
    {
        $this->resourceURI = $resourceURI;
    }

    public function registerJS(string $slug, string $resource, bool $body = true, bool $addResourceURI = true, string $after = null): void
    {
        $resource = $addResourceURI ? $this->resourceURI . $resource : $resource;
        if ($body) {
            $this->jsBody[$slug] = $resource;
        } else {
            $this->jsHeader[$slug] = $resource;
        }
        $this->collectorJs[$slug] = ['resource' => $resource, 'after' => $after, 'body' => $body];
    }

    public function registerCSS(string $slug, string $resource, bool $addResourceURI = true, string $after = null): void
    {
        $resource = $addResourceURI ? $this->resourceURI . $resource : $resource;
        $this->css[$slug] = $resource;
        $this->collectorCss[$slug] = ['resource' => $resource, 'after' => $after];
    }

    public function getJSAsStr(bool $body = true): void
    {
        if ($body) {
            foreach ($this->jsBody as $key => $item){
                echo "<script src='$item'></script>";
            }
        }
        else {
            foreach ($this->jsHeader as $key => $item){
                echo "<script src='$item'></script>";
            }
        }
    }

    public function getCSSAsSTR(): void
    {
        foreach ($this->css as $key => $item){
            echo "<link rel='stylesheet' href='$item'>";
        }
    }

    public function getCollectorCss(): array
    {
        return $this->collectorCss;
    }

    public function getCollectorJs(): array
    {
        return $this->collectorJs;
    }

}