<?php
use Mni\FrontYAML\Parser;

class Render
{
  public $loader;
  public $twig;
  public $pageInfo;
  public $menu;
  public $background;
  public function __construct()
  {
    $config = new Settings();
    $this->loader = new \Twig\Loader\FilesystemLoader("../content/themes");
    $this->twig = new \Twig\Environment($this->loader, []);
    $settings = $config->getSettings();
    $this->menu = $settings["menu"];
    $this->pageInfo = [
      "keywords" => $settings["global"]["keywords"],
      "description" => $settings["global"]["descriptions"],
      "image" => $settings["global"]["background"],
    ];
  }

  public function renderPages()
  {
    $pages = (new Book("../content/pages"))->getContents();
    $recent = [];
    $featured = [];
    $limit = 4;
    foreach ($pages as $page) {
      if (!$page["deleted"] && $page["published"]) {
        if (count($recent) < $limit) {
          array_push($recent, [
            "path" => $page["path"],
            "slug" => $page["slug"],
            "title" => $page["title"],
          ]);
        }

        if ($page["featured"] == true) {
          if (count($featured) < $limit) {
            array_push($featured, [
              "path" => $page["path"],
              "slug" => $page["slug"],
              "title" => $page["title"],
            ]);
          }
        }

        $taglist = explode(",", $page["tags"]);
        $tags = [];
        foreach ($taglist as $tag) {
          $label = trim($tag);
          array_push($tags, [
            "tag_name" => $label,
            "slug" => StringTools::safeString($label),
          ]);
        }
        $meta = [
          "who" => $page["author"],
          "when" => $page["updated"],
          "tags" => $tags,
        ];

        //render markdown content and clean it
        $parser = new Parser();
        $rendered = $parser->parse($page["content"]);
        $sanitizer = \HtmlSanitizer\Sanitizer::create([
          "extensions" => ["basic", "image", "list", "code"],
        ]);
        $preclean = $sanitizer->sanitize($rendered->getContent());
        $cleaned = strip_tags($preclean, [
          "a",
          "br",
          "p",
          "strong",
          "br",
          "img",
          "iframe",
          "ul",
          "li",
          "i",
          "h1",
          "h2",
          "h3",
          "pre",
          "code",
        ]);
        //$cleaned = preg_replace('/(?:\r\n|[\r\n]){2,}/', "\n\n", $cleaned);
        //$cleaned = html_entity_decode($cleaned, ENT_QUOTES, "UTF-8");

        if ($page["layout"] == "index") {
          $template = "fipamo-default/index.twig";
          $location = "../public/index.html";
          $dir = null;

          $pageOptions = [
            "title" => $page["title"],
            "background" => $page["feature"],
            "content" => $cleaned,
            "meta" => $meta,
            "recent" => $recent,
            "featured" => $featured,
            "info" => $this->pageInfo,
            "menu" => $this->menu,
          ];
        } else {
          $template = "fipamo-default/page.twig";
          $location =
            "../public/" . $page["path"] . "/" . $page["slug"] . ".html";
          $dir = "../public/" . $page["path"];
          $pageOptions = [
            "title" => $page["title"],
            "background" => $page["feature"],
            "content" => $cleaned,
            "meta" => $meta,
            "info" => $this->pageInfo,
            "menu" => $this->menu,
          ];
        }

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

  public function renderArchive()
  {
    $archive = Sorting::archive();
    $template = "fipamo-default/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 = "fipamo-default/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 (!is_file($location)) {
        file_put_contents($location, $html);
      } else {
        ($new = fopen($location, "w")) or die("Unable to open file!");
        fwrite($new, $html);
        fclose($new);
      }
    }
  }
}