<?php namespace Lucent\StaticGenerator;


use Carbon\Carbon;
use Illuminate\Contracts\Filesystem\Filesystem;
use Illuminate\Contracts\View\View;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use Throwable;

class StaticGenerator
{

    public function __construct(
        public Writer $writer,
        public Filesystem $filesystem
    )
    {
    }

    public function run(callable $callback): void
    {

        echo "Start ".Carbon::now()->format("Y-m-d H:i:s").PHP_EOL;
        $this->removeBuildDirectory();
        echo "Removing previous data".PHP_EOL;
        try {
            $callback($this->writer);
        }catch (Throwable $th){
            echo "Finito with errors".Carbon::now()->format("Y-m-d H:i:s")." ".$th->getMessage().PHP_EOL;
        }

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

    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);
    }


}
