<?php
use function _\find;
use function _\filter;

class Sorting
{
  private static $_tags = [];
  private static $_archive = [];
  public function __construct()
  {
  }

  public static function tags()
  {
    $pages = (new Book("../content/pages"))->getContents();
    foreach ($pages as $page) {
      $temp = [];
      $temp = explode(",", $page["tags"]);
      foreach ($temp as $tag) {
        $label = trim($tag);
        if (!find(self::$_tags, ["tag_name" => $label])) {
          array_push(self::$_tags, [
            "tag_name" => $label,
            "slug" => StringTools::safeString($label),
            "pages" => self::tagPages($label, $pages),
          ]);
        }
      }
    }

    return self::$_tags;
  }

  private static function tagPages($tag, $pages)
  {
    $tagged = [];
    foreach ($pages as $page) {
      if (strpos($page["tags"], $tag) !== false) {
        array_push($tagged, [
          "title" => $page["title"],
          "slug" => $page["slug"],
          "path" => $page["path"],
        ]);
      }
    }

    return $tagged;
  }

  public static function archive()
  {
    $pages = (new Book("../content/pages"))->getContents();
    $years = [];
    $archive = [];
    foreach ($pages as $page) {
      //$year = date("Y", date($page["rawCreated"]));
      $date = explode("/", $page["path"]);
      //echo $page["title"] . " : " . $year . "\n";
      if (!find($years, ["year" => trim($date[0])])) {
        $findPages = filter($pages, ["createdYear" => trim($date[0])]);
        //var_dump($findPages);
        array_push($years, [
          "year" => trim($date[0]),
          "count" => count($findPages),
        ]);
      }
    }
    foreach ($years as $year) {
      $sorted = [];
      $filtered = filter($pages, ["createdYear" => $year["year"]]);

      foreach ($filtered as $obj) {
        $month = date("m", date($obj["rawCreated"]));
        if (!find($sorted, ["month" => $month])) {
          $perMonth = filter($pages, [
            "path" => $year["year"] . "/" . $month,
            "deleted" => false,
            "published" => true,
            "layout" => "page",
          ]);
          array_push($sorted, [
            "month" => $month,
            "full_month" => date("F", date($obj["rawCreated"])),
            "count" => count($perMonth),
            "pages" => $perMonth,
          ]);
        }
      }
      array_push(self::$_archive, [
        "year" => $year["year"],
        "year_data" => $sorted,
      ]);
    }
    return self::$_archive;
  }
}