<?php

class PageWithHTML extends AbstractBasePage
{
    private $_widgets = array();  // will be asked for stylesheet and scriptfile information

    // Add or increment query string if a JS file changes to make sure browsers
    // reload the file (e.g. "?1" -> "?2")
    private $_early_scriptfiles = array(
        'build/bewelcome.js',
        '/script/main.js?9',
    );

    private $_late_scriptfiles = array(
        'build/offcanvas.js',
        'build/updatecounters.js',
        '/script/common/initialize.js?1',
    );

    private $_stylesheets = array(
        'build/bewelcome.css',
    );

    private $_rendered_scripts = array(
    );

    private $_rendered_stylesheets = array(
    );

    public function render() {
        $this->init();
        header('Content-type: text/html;charset="utf-8"');
        $this->printHTML();
        PVars::getObj('page')->output_done = true;
    }

    protected function init() {
        // by default, nothing happens.
        // the idea of this function is to set some values,
        // such as page title, meta keyword, meta description
    }

    /**
     * skeleton method of getCustomElements
     *
     * @access protected
     * @return array
     */
    protected function getCustomElements()
    {
        return array();
    }

    /**
     * don't forget to call
     * $stylesheets = parent::$this->getStylesheets();
     * when reimplementing this method!!
     */
    protected function getStylesheets()
    {
        $stylesheets = $this->_stylesheets;
        foreach ($this->_widgets as $widget) {
            foreach ($widget->getStylesheets() as $stylesheet) {
                $stylesheets[] = $stylesheet;
            }
        }
        return $stylesheets;
    }

    protected function getStylesheetPatches()
    {
        $stylesheet_patches = array();
        foreach ($this->_widgets as $widget) {
            foreach ($widget->getStylesheets() as $stylesheet_patches) {
                $stylesheet_patches[] = $stylesheet_patches;
            }
        }
        return $stylesheet_patches;
    }

    /**
     * returns all registered early load scripts
     * these are the scripts to be loaded in the html head element
     *
     * @access protected
     * @return array
     */
    protected function getScriptfiles()
    {
        $scriptfiles = $this->_early_scriptfiles;
        foreach ($this->_widgets as $widget) {
            foreach ($widget->getScriptfiles() as $scriptfile) {
                $scriptfiles[] = $scriptfile;
            }
        }
        return array_unique($scriptfiles);
    }

    /**
     * returns all registered late load scripts
     * these are the scripts to be loaded at the end of the page
     *
     * @access protected
     * @return array
     */
    protected function getLateLoadScriptfiles()
    {
        return array_diff(array_unique($this->_late_scriptfiles), $this->_early_scriptfiles);
    }

    /**
     * registers a script for early loading
     *
     * @param string $file - js file to early load
     *
     * @access protected
     * @return void
     */
    public function addEarlyLoadScriptFile($file)
    {
        $this->_early_scriptfiles[] = $file;
    }

    /**
     * registers a script for late loading
     *
     * @param string $file - js file to early load
     *
     * @access protected
     * @return void
     */
    public function addLateLoadScriptFile($file)
    {
        $this->_late_scriptfiles[] = $file;
    }

    public function addStylesheet($file)
    {
        $this->_stylesheets[] = $file;
    }

    protected function getPageTitle()
    {
        return 'BeWelcome';
    }


    /**
     * Widgets added this way will be asked
     * for stylesheet and scriptfile information
     * TODO: evtl not a good idea to do it this way.
     *
     * @param RoxWidget $widget
     */
    public function addWidget(RoxWidget $widget)
    {
        $this->_widgets[] = $widget;
    }


    protected function printHTML()
    {

        ?>
        <!DOCTYPE html>
        <html lang="<?=PVars::get()->lang; ?>">
        <head>
            <meta charset="utf-8">
            <meta http-equiv="X-UA-Compatible" content="IE=edge">
            <meta name="viewport" content="width=device-width, initial-scale=1">
            <link rel="icon" type="image/png" href="/images/favicon-96x96.png" sizes="96x96" />
            <link rel="icon" type="image/svg+xml" href="/images/favicon.svg" />
            <link rel="shortcut icon" href="/images/favicon.ico" />
            <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon.png" />
            <meta name="apple-mobile-web-app-title" content="beWelcome" />

        <!-- this page is generated by "class <?=get_class($this) ?>" -->
        <!-- the controller was an instance of <?=(is_string($this->controller_classname) ? ('"class '.$this->controller_classname.'"') : '[unknown class]') ?> -->
        <?=(is_object($this->layoutkit) && is_object($this->layoutkit->mem_from_redirect) ? '
        <!--
        '.$this->layoutkit->mem_from_redirect->buffered_text.'
        -->' : '') ?>
        <?php
        $this->head();
        $this->includeJsConfig();
        $this->includeScriptfiles();
        ?>
        </head>
        <body>
        <?php $this->topmenu() ?>
        <main role="main">
        <?php

        echo (is_object($this->layoutkit) && (is_object($this->layoutkit->mem_from_redirect))) ? $this->layoutkit->mem_from_redirect->buffered_text : '';

        $this->body();
        ?>
        </main>
        <?php
            $this->footer();
            $this->includeLateScriptfiles();
        ?>
        <script type="application/javascript">
            $('[data-toggle="dropdown"]').bootstrapDropdownHover({
                clickBehavior: 'sticky',
                hideTimeout: 1000
            });
        </script>
        </body>
        </html><?php
    }

    protected function printStylesheetTags($stylesheetUrl)
    {
        if (false === strpos($stylesheetUrl, 'build/'))
        {
            echo '<link rel="stylesheet" href="' . $stylesheetUrl . '">' . PHP_EOL;
        }
        else
        {
            $stylesheetFile = str_replace('build/', '', $stylesheetUrl);
            $stylesheetFile = str_replace('.css', '', $stylesheetFile);
            $stylesheetFiles = $this->entryPointLookup->getCssFiles($stylesheetFile);
            foreach ($stylesheetFiles as $stylesheetFile) {
                if (!isset($this->_rendered_stylesheets[$stylesheetFile])) {
                    echo '<link rel="stylesheet" href="' . $stylesheetFile . '">' . PHP_EOL;
                    $this->_rendered_stylesheets[$stylesheetFile] = $stylesheetFile;
                }
            }
        }
    }

    protected function printScriptTags($scriptUrl)
    {
        if (false === strpos($scriptUrl, 'build/') || false !== strpos($scriptUrl, 'cktranslations/'))
        {
            echo '<script src="' .  ltrim($scriptUrl, '/') . '"></script>' . PHP_EOL;
        }
        else
        {
            $scriptFile = str_replace('build/', '', $scriptUrl);
            $scriptFile = str_replace('.js', '', $scriptFile);
            $scriptFiles = $this->entryPointLookup->getJavaScriptFiles($scriptFile);
            foreach($scriptFiles as $scriptFile) {
                if (!isset($this->_rendered_scripts[$scriptFile])) {
                    echo '<script src="' . $scriptFile . '"></script>' . PHP_EOL;
                    $this->_rendered_scripts[$scriptFile] = $scriptFile;
                }
            }
        }
    }

    protected function includeStylesheets()
    {
        if (!$stylesheetUrls = $this->getStylesheets()) {
            return;
        }

        foreach($stylesheetUrls as $stylesheetUrl) {
            $this->printStylesheetTags($stylesheetUrl);
        }
    }

    /**
     * allows for outputting custom elements in the page <head> element
     *
     * @access protected
     */
    protected function includeCustomElements()
    {
        if ($elements = $this->getCustomElements())
        {
            foreach($elements as $element)
            {
                echo $element . PHP_EOL;
            }
        }
    }

    /**
     * Inserts JavaScript configuration.
     *
     * Reads [javascript] section in rox.ini and makes it available via
     * bwroxConfig object in JavaScript.
     */
    protected function includeJsConfig()
    {
        $config = PVars::getArray('javascript');
        if ($config) {
            $html = array();
            $pairs = array();
            $html[] = '<script type="text/javascript">';
            $html[] = 'var bwroxConfig = {';
            foreach($config as $key => $value) {
                $pairs[] = $key . ": '" . $value . "'";
            }
            $html[] = implode(',', $pairs);
            $html[] = '}';
            $html[] = '</script>';
            echo implode("\n", $html);
        }
    }

    protected function includeScriptfiles()
    {
        if (!$scriptUrls = $this->getScriptfiles()) {
            return;
        }

        foreach($scriptUrls as $scriptUrl) {
            $this->printScriptTags($scriptUrl);
        }
    }

    /**
     * outputs script tags that include script files
     * called at the end of pages
     *
     * @access protected
     * @return void
     */
    protected function includeLateScriptfiles()
    {
        if (!$scriptUrls = $this->getLateLoadScriptfiles()) {
            return;
        }

        foreach($scriptUrls as $scriptUrl) {
            $this->printScriptTags($scriptUrl);
        }
    }

    protected function head()
    {
        $baseuri = PVars::getObj('env')->baseuri ?: '/';
        ?>
        <title><?= htmlspecialchars($this->getPageTitle(), ENT_QUOTES) ?></title>
        <base id="baseuri" href='<?=$baseuri ?>' />
        <meta name="verify-v1" content="NzxSlKbYK+CRnCfULeWj0RaPCGNIuPqq10oUpGAEyWw=" />
        <meta name="description" content="<?=$this->getPage_meta_description()?>" />
        <meta name="keywords" content="<?=$this->getPage_meta_keyword()?>" />
        <meta name="robots" content="<?=$this->getPage_meta_robots()?>" />
        <?php
        $this->includeStylesheets();
        $this->includeCustomElements();
        $this->_tr_buffer_header = $this->getWords()->flushBuffer();
    }

    protected function getPagePermalink() {
        return 'index';
    }

    protected function getSubmenuItems()
    {
        return [];
    }
}
