<?php

namespace brain\data;

use brain\utility\Sorting;
use brain\utility\DocTools;

use function _\find;

class Render
{
    public $loader;
    public $twig;
    public $pageInfo;
    public $menu;
    public $background;

    public function __construct()
    {
        $config = new Settings();
        //TODO: Add theme folder to loader
        $settings       = $config->getSettings();
        $this->menu     = $settings['menu'];
        $this->theme    = $settings['global']['theme'];
        $this->loader   = new \Twig\Loader\FilesystemLoader('../content/themes/' . $this->theme);
        $this->twig     = new \Twig\Environment($this->loader, []);
        $this->pageInfo = [
            'keywords' => isset($settings['global']['keywords'])
                ? $settings['global']['keywords']
                : 'fipamo, blog, jamstack, php, markdown, js',
            'description' => $settings['global']['descriptions'],
            'image'       => $settings['global']['base_url'] . $settings['global']['background'],
            'baseURL'     => $settings['global']['base_url'],
        ];
        //move global theme image assets to public folder
        foreach (
            new \DirectoryIterator('../content/themes/' . $this->theme . '/assets/images/global/') as $file
        ) {
            if ($file->isDot()) {
                continue;
            }
            if (!is_file('../public/assets/images/global/' . $file->getFileName())) {
                copy(
                    '../content/themes/' .
                        $this->theme .
                        '/assets/images/global/' .
                        $file->getFileName(),
                    '../public/assets/images/global/' . $file->getFileName()
                );
            } else {
                //image is already there, so chill
            }
            //print $file->getFilename() . "\n";
        }

        //copy current theme assets to public

        //clear files in css and scripts folder
        $styles = glob('../public/assets/css/*'); // get all file names
        foreach ($styles as $file) { // iterate files
            if (is_file($file)) {
                //don't erase dashboard css
                if (!$file == '../public/assets/css/dash.css') {
                    unlink($file); // delete file
                }
            }
        }

        $scripts = glob('../public/assets/scripts/*'); // get all file names
        foreach ($scripts as $file) { // iterate files
            if (is_file($file)) {
                if (!$file == '../public/assets/scripts/Start.js') {
                    unlink($file); // delete file
                }
            }
        }
        //copy theme assets to public
        $newcss = glob('../content/themes/' . $this->theme . '/assets/css/*');
        foreach ($newcss as $file) { // iterate files
            if (is_file($file)) {
                $path = explode('/', $file);
                copy($file, '../public/assets/css/' . $path[6]);
            }
        }
        $newjs = glob('../content/themes/' . $this->theme . '/assets/scripts/*');
        foreach ($newjs as $file) { // iterate files
            if (is_file($file)) {
                $path = explode('/', $file);
                copy($file, '../public/assets/scripts/' . $path[6]);
            }
        }
    }

    public function renderPages()
    {
        $pages    = (new Book())->getContents();
        $recent   = [];
        $featured = [];
        $limit    = 4;
        foreach ($pages as $page) {
            $pageOptions = Sorting::page($page);

            $layout = $page['layout'];
            //new pages have no layout, so defautl for now
            if ($layout == '' || $layout == null) {
                $layout = 'page';
            }

            $template = $layout . '.twig';
            if (str_contains($page['layout'], 'index')) {
                $location = '../public/index.html';
                $dir      = null;
            } else {
                // if page is a menu item, render the page on public root
                if ($page['menu'] == 'true') {
                    $location = '../public/' . $page['slug'] . '.html';
                    $dir      = '../public/';
                } else {
                    $location = '../public/' . $page['path'] . '/' . $page['slug'] . '.html';
                    $dir      = '../public/' . $page['path'];
                }
            }

            $html = $this->twig->render($template, $pageOptions);
            DocTools::writeHTML($location, $html, $dir);
        }
    }

    public function renderArchive()
    {
        $archive     = Sorting::archive();
        $template    = 'archive.twig';
        $pageOptions = [
            'title'      => 'Archive',
            'background' => $this->pageInfo['image'],
            'archives'   => $archive,
            'info'       => $this->pageInfo,
            'menu'       => $this->menu,
        ];

        $html     = $this->twig->render($template, $pageOptions);
        $location = '../public/archives.html';
        DocTools::writeHTML($location, $html);
    }

    public function renderTags()
    {
        $list = Sorting::tags();
        foreach ($list as $item) {
            $template    = 'tags.twig';
            $pageOptions = [
                'title'      => 'Pages Tagged as ' . $item['tag_name'],
                'background' => $this->pageInfo['image'],
                'tag_list'   => $item['pages'],
                'info'       => $this->pageInfo,
                'menu'       => $this->menu,
            ];

            $html = $this->twig->render($template, $pageOptions);

            $location = '../public/tags/' . $item['slug'] . '.html';

            //if tags folder doesn't exist, make it
            if (!is_dir('../public/tags')) {
                mkdir('../public/tags', 0755, true);
            } else {
            }

            if (!is_file($location)) {
                file_put_contents($location, $html);
            } else {
                ($new = fopen($location, 'w')) or die('Unable to open file!');
                fwrite($new, $html);
                fclose($new);
            }
        }
    }

    public function renderIndex()
    {
        //TODO: Need to fix this to account for new index templating system
        $pages    = (new Book())->getContents();
        $index    = find($pages, ['layout' => 'index']);
        $template = 'index.twig';
        $location = '../public/index.html';
        $dir      = null;

        $meta = [
            'who'  => $index['author'],
            'when' => $index['created'],
        ];

        $pageOptions = [
            'title'      => $index['title'],
            'background' => $index['feature'],
            'meta'       => $meta,
        ];

        $html = $this->twig->render($template, $pageOptions);
        DocTools::writeHTML($location, $html, $dir);
    }
}