// /***************************************************************************
// Aaru Data Preservation Suite
// ----------------------------------------------------------------------------
//
// Filename       : Read.cs
// Author(s)      : Natalia Portillo <claunia@claunia.com>
//
// Component      : Disk image plugins.
//
// --[ Description ] ----------------------------------------------------------
//
//     Reads Digital Research's DISKCOPY disk images.
//
// --[ 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.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Aaru.CommonTypes;
using Aaru.CommonTypes.Enums;
using Aaru.CommonTypes.Interfaces;
using Aaru.Helpers;
using Aaru.Logging;

namespace Aaru.Images;

public sealed partial class DriDiskCopy
{
#region IWritableImage Members

    /// <inheritdoc />
    public ErrorNumber Open(IFilter imageFilter)
    {
        Stream stream = imageFilter.GetDataForkStream();

        if((stream.Length - Marshal.SizeOf<Footer>()) % 512 != 0) return ErrorNumber.InvalidArgument;

        var buffer = new byte[Marshal.SizeOf<Footer>()];
        stream.Seek(-buffer.Length, SeekOrigin.End);
        stream.EnsureRead(buffer, 0, buffer.Length);

        _footer = Marshal.ByteArrayToStructureLittleEndian<Footer>(buffer);

        string sig = StringHandlers.CToString(_footer.signature);

        Regex regexSignature = DriRegex();
        Match matchSignature = regexSignature.Match(sig);

        if(!matchSignature.Success) return ErrorNumber.InvalidArgument;

        if(_footer.bpb.sptrack * _footer.bpb.cylinders * _footer.bpb.heads != _footer.bpb.sectors)
            return ErrorNumber.InvalidArgument;

        if(_footer.bpb.sectors * _footer.bpb.bps + Marshal.SizeOf<Footer>() != stream.Length)
            return ErrorNumber.InvalidArgument;

        _imageInfo.Cylinders          = _footer.bpb.cylinders;
        _imageInfo.Heads              = _footer.bpb.heads;
        _imageInfo.SectorsPerTrack    = _footer.bpb.sptrack;
        _imageInfo.Sectors            = _footer.bpb.sectors;
        _imageInfo.SectorSize         = _footer.bpb.bps;
        _imageInfo.ApplicationVersion = matchSignature.Groups["version"].Value;

        _driImageFilter = imageFilter;

        _imageInfo.ImageSize            = (ulong)(stream.Length - Marshal.SizeOf<Footer>());
        _imageInfo.CreationTime         = imageFilter.CreationTime;
        _imageInfo.LastModificationTime = imageFilter.LastWriteTime;

        AaruLogging.Debug(MODULE_NAME,
                          Localization.Image_application_0_version_1,
                          _imageInfo.Application,
                          _imageInfo.ApplicationVersion);

        // Correct some incorrect data in images of NEC 2HD disks
        if(_imageInfo is { Cylinders: 77, Heads: 2 } and { SectorsPerTrack: 16, SectorSize: 512 } &&
           _footer.bpb._driveCode is DriveCode.md2hd or DriveCode.mf2hd)
        {
            _imageInfo.SectorsPerTrack = 8;
            _imageInfo.SectorSize      = 1024;
        }

        _imageInfo.MediaType = Geometry.GetMediaType(((ushort)_imageInfo.Cylinders, (byte)_imageInfo.Heads,
                                                      (ushort)_imageInfo.SectorsPerTrack, _imageInfo.SectorSize,
                                                      MediaEncoding.MFM, false));

        switch(_imageInfo.MediaType)
        {
            case MediaType.NEC_525_HD when _footer.bpb._driveCode is DriveCode.mf2hd or DriveCode.mf2ed:
                _imageInfo.MediaType = MediaType.NEC_35_HD_8;

                break;
            case MediaType.DOS_525_HD when _footer.bpb._driveCode is DriveCode.mf2hd or DriveCode.mf2ed:
                _imageInfo.MediaType = MediaType.NEC_35_HD_15;

                break;
            case MediaType.RX50 when _footer.bpb._driveCode is DriveCode.md2dd or DriveCode.md2hd:
                _imageInfo.MediaType = MediaType.ATARI_35_SS_DD;

                break;
        }

        _imageInfo.MetadataMediaType = MetadataMediaType.BlockMedia;

        AaruLogging.Verbose(Localization.Digital_Research_DiskCopy_image_contains_a_disk_of_type_0,
                            _imageInfo.MediaType);

        return ErrorNumber.NoError;
    }

    /// <inheritdoc />
    public ErrorNumber ReadSector(ulong sectorAddress, bool negative, out byte[] buffer, out SectorStatus sectorStatus)
    {
        sectorStatus = SectorStatus.Dumped;

        return ReadSectors(sectorAddress, negative, 1, out buffer, out _);
    }

    /// <inheritdoc />
    public ErrorNumber ReadSectors(ulong              sectorAddress, bool negative, uint length, out byte[] buffer,
                                   out SectorStatus[] sectorStatus)
    {
        buffer       = null;
        sectorStatus = null;

        if(negative) return ErrorNumber.NotSupported;

        if(sectorAddress > _imageInfo.Sectors - 1) return ErrorNumber.OutOfRange;

        if(sectorAddress + length > _imageInfo.Sectors) return ErrorNumber.OutOfRange;

        buffer       = new byte[length * _imageInfo.SectorSize];
        sectorStatus = Enumerable.Repeat(SectorStatus.Dumped, (int)length).ToArray();

        Stream stream = _driImageFilter.GetDataForkStream();
        stream.Seek((long)(sectorAddress          * _imageInfo.SectorSize), SeekOrigin.Begin);
        stream.EnsureRead(buffer, 0, (int)(length * _imageInfo.SectorSize));

        return ErrorNumber.NoError;
    }

#endregion
}