//
// FileReader.cs
//
// Copyright (c) František Boháček. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Runtime.InteropServices;
using NosSmooth.Data.NOSFiles.Errors;
using NosSmooth.Data.NOSFiles.Files;
using Remora.Results;
namespace NosSmooth.Data.NOSFiles.Readers;
///
/// Reader of files.
///
public class FileReader
{
private readonly IReadOnlyList _typeReaders;
///
/// Initializes a new instance of the class.
///
/// The readers of specific types.
public FileReader(IEnumerable typeReaders)
{
_typeReaders = typeReaders.ToArray();
}
///
/// Get a file type reader for the given file.
///
/// The file.
/// A type reader or an error.
public Result GetFileTypeReader(RawFile file)
{
foreach (var typeReader in _typeReaders)
{
if (typeReader.SupportsFile(file))
{
return Result.FromSuccess(typeReader);
}
}
return new UnknownFileTypeError(file);
}
///
/// Read the given file.
///
/// The raw file.
/// The type of the content to assume.
/// The content or an error.
public Result> Read(RawFile file)
{
var fileReaderResult = GetFileTypeReader(file);
if (!fileReaderResult.IsSuccess)
{
return Result>.FromError(fileReaderResult);
}
var fileReader = fileReaderResult.Entity;
var readResult = fileReader.Read(file);
if (!readResult.IsSuccess)
{
return Result>.FromError(readResult);
}
try
{
var content = (ReadFile)readResult.Entity;
return content;
}
catch (Exception e)
{
return e;
}
}
///
/// Read a file from a filesystem path.
///
/// The path to the file.
/// The type of the content to assume.
/// The content or an error.
public Result> ReadFileSystemFile(string path)
{
try
{
var readData = File.ReadAllBytes(path);
return Read(new RawFile(null, path, readData.Length, readData));
}
catch (Exception e)
{
return e;
}
}
}