<?php

namespace Bakgul\FileHistory\Services;

use Bakgul\FileContent\Helpers\Content;
use Bakgul\FileHistory\Helpers\Log;
use Bakgul\FileHistory\Helpers\Settings;
use Bakgul\LaravelHelpers\Helpers\Arr;
use Bakgul\LaravelHelpers\Helpers\Folder;
use Bakgul\LaravelHelpers\Helpers\Path;

class LogService
{
    protected static $path;
    protected static $file;
    protected static $content;
    protected static $isRename;

    public static function getLogs(): array
    {
        return json_decode(file_get_contents(Settings::file()), true);
    }

    public static function getLastUnprefixedFile(string $path): string
    {
        return self::path($path, Arr::fetch(self::getUnprefixedFiles($path), -1) ?: '');
    }

    public static function getUnprefixedFiles(string $path): array
    {
        return self::getFiles($path, fn ($x) => !str_contains($x, Log::prefix()));
    }

    public static function getFirstPrefixedFile(string $path): string
    {
        return self::path($path, Arr::fetch(self::getPrefixedFiles($path), 0) ?: '');
    }

    public static function getPrefixedFiles(string $path): array
    {
        return self::getFiles($path, fn ($x) => str_contains($x, Log::prefix()));
    }

    private static function path($path, $file)
    {
        return $file ? Path::glue([$path, $file]) : '';
    }

    public static function getFiles(string $path, callable $callback = null)
    {
        return array_filter(Folder::content($path), $callback);
    }

    public static function write()
    {
        Content::writeJson(Settings::file(), self::$content);
    }
}
