<?php namespace Lucent\StaticGenerator;


use Carbon\Carbon;
use Illuminate\Contracts\Filesystem\Filesystem;
use Lucent\Command\CommandService;
use Throwable;

class StaticGenerator
{

    public function __construct(
        public Filesystem     $filesystem,
        public CommandService $commandService,
    )
    {
    }

    public function run(string $signature, callable $callback): void
    {
        $logWriter = $this->commandService->logWriter($signature);
        $logWriter("Start " . Carbon::now()->format("Y-m-d H:i:s"));
        $this->removeBuildDirectory();
        $logWriter("Removing previous data");
        try {
            $callback(new Writer($logWriter));
        } catch (Throwable $th) {
            $logWriter("Finished with errors" . Carbon::now()->format("Y-m-d H:i:s") . " " . $th->getMessage());
        }

        $this->copyBuildDirectory();
        $logWriter("Finished " . Carbon::now()->format("Y-m-d H:i:s"));
    }

    private function removeBuildDirectory(): void
    {
        if (!file_exists(storage_path("lucent/build"))) {
            return;
        }
        $cmd = "rm -rf " . storage_path("lucent/build");
        exec($cmd);
    }

    private function copyBuildDirectory(): void
    {
        if (file_exists(storage_path("lucent/live"))) {
            $cmd = "rm -rf " . storage_path("lucent/live");
            exec($cmd);
        }
        $cmd = sprintf("cp -R %s %s", storage_path("lucent/build"), storage_path("lucent/live"));
        exec($cmd);
    }


}
