<?php

class MapBox
{
    protected $doc;
    protected $baseUrl;
    protected $assetsUrl;
    protected $entryPoint = 'public';
    protected $manifest = [];
    protected $admin = false;

    public function __construct($admin = false)
    {
        $this->doc = JFactory::getDocument();
        $this->baseUrl = JUri::root(true);
        $this->admin = $admin;
        if ($admin) {
            $this->entryPoint = 'admin';
        }
        $this->assetsUrl = "$this->baseUrl/media/mod_mapbox";
        $this->manifest['modern'] = json_decode(file_get_contents(JPATH_ROOT . '/media/mod_mapbox/manifest.json'), true);
        $this->manifest['legacy'] = json_decode(file_get_contents(JPATH_ROOT . '/media/mod_mapbox/manifest-legacy.json'), true);
    }

    private function attachScripts()
    {
        $this->addScript($this->manifest['modern']["$this->entryPoint.js"], ['type' => 'module']);
        $this->addScript($this->manifest['modern']["chunk-common.js"], ['type' => 'module']);

        $this->addScript($this->manifest['legacy']["$this->entryPoint.js"], ['nomodule' => true]);
        $this->addScript($this->manifest['legacy']["chunk-common.js"], ['nomodule' => true]);
    }

    private function attachStyles()
    {
        $this->doc->addStyleSheet('https://api.tiles.mapbox.com/mapbox-gl-js/v0.49.0/mapbox-gl.css');
        if ($this->admin) {
            $this->doc->addStyleSheet('https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-geocoder/v2.3.0/mapbox-gl-geocoder.css');
        }
        $this->addStyleSheet($this->manifest['modern']["$this->entryPoint.css"]);
        $this->addStyleSheet($this->manifest['modern']["chunk-common.css"]);
    }

    private function addScript(string $script, array $options = [])
    {
        $this->doc->addScript("$this->assetsUrl/$script", array_merge([
            'defer' => true,
            'async' => true,
        ]), $options);
    }

    private function addStyleSheet(string $style)
    {
        $this->doc->addStyleSheet("$this->assetsUrl/$style");
    }

    public function render($value, $name = null)
    {
        $this->attachScripts();
        $this->attachStyles();

        if ($name) {
            return "<div id='app' data-name='$name' data-value='$value' data-baseurl='$this->baseUrl'></div>";
        }

        return "<div id='app' data-value='$value' data-baseurl='$this->baseUrl'></div>";
    }
}
