<?php namespace Lucent\StaticGenerator;


use Illuminate\Contracts\View\View;

class Writer
{


    public function __construct()
    {
    }

    private function buildPath(string $path): string
    {
        if (!file_exists(storage_path("lucent/build"))) {
            mkdir(storage_path("lucent/build"));
        }
        return storage_path("lucent/build/" . ltrim($path, "/"));
    }

    public function save(string $path, string $html, string $extension = "html"): void
    {
        $filepath = $this->buildPath($path. "/index.$extension");

        if (!file_exists(pathinfo($filepath, PATHINFO_DIRNAME))) {
            make_dir_r(pathinfo($filepath, PATHINFO_DIRNAME));
        }
        file_put_contents($filepath, $html);
        echo "Path: $path" . PHP_EOL;
    }



    public function recordIterator(callable $query, callable $parser, int $skip = 0, $limit = 100): int
    {
        // logger("fetching $skip");

        $records = $query($limit, $skip);
        $parser($records, $limit, $skip);

        if ($records->count() > 0) {
            return $this->recordIterator($query, $parser, $skip + $limit);
        }

        return 0;
    }

    public function createRedirect(string $from, string $to, string $title = "Redirecting", string $message = "Redirecting Soon..."): void
    {
        $html = view("lucent::redirect", [
            "to" => $to,
            "title" => $title,
            "message" => $message,
        ])->render();
        $this->save($from, $html);
    }
}
