using System.IO.Compression;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization.Formatters.Binary;

namespace Universal;

public class Compressor
{
    public static bool CompressZipFileDirectory(DirectoryInfo sourceDirectory, DirectoryInfo zipFilePath, string fileName, out string? fullZippedPath)
    {
        fullZippedPath = null;

        if (!sourceDirectory.Exists)
            return false;

        if (string.IsNullOrEmpty(fileName))
            return false;

        if (!fileName.EndsWith(".zip"))
            fileName = $"{fileName}.zip";

        fullZippedPath = Path.Combine(zipFilePath.FullName, fileName);
        try
        {
            ZipFile.CreateFromDirectory(sourceDirectory.FullName, fullZippedPath, CompressionLevel.SmallestSize, false);
        }
        catch
        {
            return false;
        }

        return true;
    }

    public static bool CompressZipFileDirectory(DirectoryInfo sourceDirectory, Stream stream)
    {
        if (!sourceDirectory.Exists)
            return false;

        try
        {
            ZipFile.CreateFromDirectory(sourceDirectory.FullName, stream, CompressionLevel.SmallestSize, false);
        }
        catch
        {
            return false;
        }

        return true;
    }

    public static bool DecompressZipFile(string path, Stream stream)
    {

        try
        {
            DirectoryInfo directory = new(path);
            if (!directory.Exists)
                directory.Create();

            ZipFile.ExtractToDirectory(stream, path, true);

        }
        catch
        {

            return false;
        }

        return true;
    }
}
