<?php
use Mni\FrontYAML\Parser;
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
    $this->loader = new \Twig\Loader\FilesystemLoader("../content/themes");
    $this->twig = new \Twig\Environment($this->loader, []);
    $settings = $config->getSettings();
    $this->menu = $settings["menu"];
    $this->theme = $settings["global"]["theme"];
    $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
    //TODO: change to just grab directory contents for scripts and css
    if (is_file("../public/assets/css/base.css")) {
      unlink("../public/assets/css/base.css");
    }
    copy(
      "../content/themes/" . $this->theme . "/assets/css/base.css",
      "../public/assets/css/base.css"
    );
    if (is_file("../public/assets/scripts/start.min.js")) {
      unlink("../public/assets/scripts/start.min.js");
    }
    copy(
      "../content/themes/" . $this->theme . "/assets/scripts/start.min.js",
      "../public/assets/scripts/start.min.js"
    );
  }

  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 = $this->theme . "/" . $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 = $this->theme . "/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 = $this->theme . "/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 = $this->theme . "/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);
  }
}