// /***************************************************************************
// Aaru Data Preservation Suite
// ----------------------------------------------------------------------------
//
// Filename       : Dir.cs
// Author(s)      : Natalia Portillo <claunia@claunia.com>
//
// Component      : Microsoft NT File System plugin.
//
// --[ License ] --------------------------------------------------------------
//
//     This library is free software; you can redistribute it and/or modify
//     it under the terms of the GNU Lesser General Public License as
//     published by the Free Software Foundation; either version 2.1 of the
//     License, or (at your option) any later version.
//
//     This library is distributed in the hope that it will be useful, but
//     WITHOUT ANY WARRANTY; without even the implied warranty of
//     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
//     Lesser General Public License for more details.
//
//     You should have received a copy of the GNU Lesser General Public
//     License along with this library; if not, see <http://www.gnu.org/licenses/>.
//
// ----------------------------------------------------------------------------
// Copyright © 2011-2026 Natalia Portillo
// ****************************************************************************/

using System;
using System.Collections.Generic;
using System.Linq;
using Aaru.CommonTypes.Enums;
using Aaru.CommonTypes.Interfaces;

namespace Aaru.Filesystems;

/// <inheritdoc />
public sealed partial class NTFS
{
    /// <inheritdoc />
    public ErrorNumber OpenDir(string path, out IDirNode node)
    {
        node = null;

        if(!_mounted) return ErrorNumber.AccessDenied;

        // Normalize path
        string normalizedPath = string.IsNullOrWhiteSpace(path) ? "/" : path;

        if(!normalizedPath.StartsWith("/", StringComparison.Ordinal)) normalizedPath = "/" + normalizedPath;

        // Root directory case
        if(normalizedPath == "/")
        {
            if(_rootDirectoryCache == null) return ErrorNumber.InvalidArgument;

            node = new NtfsDirNode
            {
                Path     = "/",
                Position = 0,
                Entries  = _rootDirectoryCache.Keys.OrderBy(static k => k, StringComparer.OrdinalIgnoreCase).ToArray()
            };

            return ErrorNumber.NoError;
        }

        // Parse path components
        string cutPath = normalizedPath[1..]; // Remove leading '/'

        string[] pieces = cutPath.Split(['/'], StringSplitOptions.RemoveEmptyEntries);

        if(pieces.Length == 0) return ErrorNumber.NoSuchFile;

        // Start from root directory
        Dictionary<string, ulong> currentDirectory = _rootDirectoryCache;

        // Traverse through path components
        for(var p = 0; p < pieces.Length; p++)
        {
            string component = pieces[p];

            // Look for the component in current directory (case-insensitive via dictionary comparer)
            if(!currentDirectory.TryGetValue(component, out ulong mftRef)) return ErrorNumber.NoSuchFile;

            // Read directory entries for this MFT record
            ErrorNumber errno =
                ReadDirectoryEntries((uint)(mftRef & 0x0000FFFFFFFFFFFF), out Dictionary<string, ulong> dirEntries);

            if(errno != ErrorNumber.NoError)
            {
                // If the entry is not a directory, return appropriate error
                if(errno == ErrorNumber.NotDirectory && p < pieces.Length - 1) return ErrorNumber.NotDirectory;

                if(errno == ErrorNumber.NotDirectory) return errno;

                return errno;
            }

            // If this is the last component, we're opening this directory
            if(p == pieces.Length - 1)
            {
                node = new NtfsDirNode
                {
                    Path     = normalizedPath,
                    Position = 0,
                    Entries  = dirEntries.Keys.OrderBy(static k => k, StringComparer.OrdinalIgnoreCase).ToArray()
                };

                return ErrorNumber.NoError;
            }

            // Not the last component - move to next level
            currentDirectory = dirEntries;
        }

        return ErrorNumber.NoSuchFile;
    }

    /// <inheritdoc />
    public ErrorNumber CloseDir(IDirNode node)
    {
        if(node is not NtfsDirNode mynode) return ErrorNumber.InvalidArgument;

        mynode.Position = -1;
        mynode.Entries  = null;

        return ErrorNumber.NoError;
    }

    /// <inheritdoc />
    public ErrorNumber ReadDir(IDirNode node, out string filename)
    {
        filename = null;

        if(!_mounted) return ErrorNumber.AccessDenied;

        if(node is not NtfsDirNode mynode) return ErrorNumber.InvalidArgument;

        if(mynode.Position < 0) return ErrorNumber.InvalidArgument;

        // End of directory
        if(mynode.Position >= mynode.Entries.Length) return ErrorNumber.NoError;

        // Get current filename and advance position
        filename = mynode.Entries[mynode.Position++];

        return ErrorNumber.NoError;
    }
}