using System.Threading;
using Dpz.Core.Public.ViewModel;
using Dpz.Core.Service.RepositoryService;

namespace Dpz.Core.Service;

public static class CodeNoteTreeExtensions
{
    public static async Task<CodeNoteTree> BuildCodeNoteTreeAsync(
        this ICodeFileSystemEntryService codeFileSystemEntryService,
        IEnumerable<string>? pathSegments,
        CancellationToken cancellationToken = default
    )
    {
        var normalizedPathSegments = pathSegments
            ?.Where(x => !string.IsNullOrWhiteSpace(x))
            .ToArray();
        var isRoot = normalizedPathSegments is null || normalizedPathSegments.Length == 0;
        var currentEntry = isRoot
            ? null
            : await codeFileSystemEntryService.FindByPathAsync(
                normalizedPathSegments,
                cancellationToken
            );

        if (!isRoot && currentEntry == null)
        {
            return CodeNoteTree.NotFound(normalizedPathSegments);
        }

        if (isRoot || currentEntry is { IsDirectory: true })
        {
            var children = await codeFileSystemEntryService.GetChildrenAsync(
                currentEntry?.PathSegments,
                cancellationToken
            );
            return CodeNoteTree.FromDirectory(currentEntry?.PathSegments, children, currentEntry);
        }

        var safePaths = currentEntry?.PathSegments ?? [];
        return CodeNoteTree.FromFile(safePaths, currentEntry!);
    }
}
评论加载中...