<?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 = json_decode(file_get_contents(JPATH_ROOT . '/media/mod_mapbox/manifest.json'), true);
    }

    private function attachScripts()
    {
        $this->addScript($this->manifest["$this->entryPoint.js"] );
        $this->addScript($this->manifest["chunk-vendors.js"] );
    }

    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["$this->entryPoint.css"]);
    }

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

    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>";
    }
}
