using System;
using System.IO;
using System.Linq;
using KattekerCreator.Exceptions;
using KattekerCreator.Helper;
using System.Diagnostics.CodeAnalysis;

namespace KattekerCreator.Types
{
    internal static class SevenZip
    {
        private const string SevenZipExecutable = "7za.exe";
        private const string SevenZipDirectory = "7zip";
        public const string ArchiveName = "app.package";

        private static readonly string BaseDirectory =
            Path.Combine(Utils.BaseDirectory, SevenZipDirectory);

        public static string Initialize()
        {
            if (!Directory.Exists(BaseDirectory)) throw new KattekerCreatorException("NSIS directory not found.");
            return TryGetSevenZipFilePath(out var path) ? path : throw new KattekerCreatorException("7-zip not found");
        }

        private static bool TryGetSevenZipFilePath([NotNullWhen(true)] out string? path)
        {
            var files = Directory.EnumerateFiles(BaseDirectory, "*.exe", SearchOption.AllDirectories);
            path = files.FirstOrDefault(x =>
                x.EndsWith(SevenZipExecutable, StringComparison.InvariantCultureIgnoreCase));
            return path != default;
        }
    }
}