<?php

final class Portfolio
{

    private array $links = [];

    public function __construct()
    {
        $this->loadConfig();
    }

    public function run()
    {
        $this->render();
    }

    private function loadConfig()
    {
        require_once "config.php";
        foreach ($links as $id => $link) {
            $this->links[] = new Link($id, $link["label"], $link["url"], $link["self"]);
        }
    }

    private function render()
    {
        $title = PORTFOLIO_TITLE;
        $url = PORTFOLIO_URL;
        $galleries = $this->loadGalleries();
        $links = $this->links;
        $footer = PORTFOLIO_CREATION_YEAR . " - " . getdate()["year"] .
            ". " . AUTHOR_NICKNAME .
            (AUTHOR_REALNAME !== "" ? " (" . AUTHOR_REALNAME . ")" : "");
        $has_subfooter = PORTFOLIO_SUBFOOTER !== "";
        $subfooter = PORTFOLIO_SUBFOOTER;
        include "views/index.phtml";
    }

    private function loadGalleries(): array
    {
        $galleries = [];
        foreach (array_diff(scandir("./galleries"), [".", ".."]) as $dir) {
            $path = "./galleries/$dir";
            $meta = "$path/metadata.txt";
            if (!is_file($meta)) {
                continue;
            }
            $galleries[] = $this->loadGallery($path, trim(file_get_contents($meta)));
        }
        return $galleries;
    }

    private function loadGallery(string $dir, string $title): Gallery
    {
        $gallery = new Gallery($title);
        foreach (array_diff(scandir($dir, SCANDIR_SORT_DESCENDING), [".", ".."]) as $file) {
            $path = "$dir/$file";
            $meta = "$path.meta.txt";
            if (!is_file($meta)) {
                continue;
            }
            $gallery->add($this->loadImage($dir, $file, $meta));
        }
        return $gallery;
    }

    private function loadImage(string $dir, string $file, string $meta): Image
    {
        $path = "$dir/" . rawurlencode($file);
        $thumbnail = str_replace(".jpg", "_thb.jpg", $path);
        list($title, $alt) = file($meta);
        list($width, $height) = getimagesize("$dir/$file");
        return new Image(
            $path,
            $thumbnail,
            trim($title),
            trim($alt),
            (int) $width,
            (int) $height
        );
    }
}