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

namespace KattekerCreator.Types
{
    internal static class Nsis
    {
        private const string MakeNsisExecutable = "makensis.exe";
        private const string MakeNsisDirectory = "nsis";

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

        public static string Initialize()
        {
            if (!Directory.Exists(BaseDirectory)) throw new KattekerCreatorException("NSIS directory not found.");
            if (TryGetMakeNsisFilePath(out var path)) return path;
            Log.Information("Unpacking NSIS for first use");
            return TryUnpackZipFile(out path) ? path : throw new KattekerCreatorException("MakeNSIS not found");
        }

        private static bool TryUnpackZipFile([NotNullWhen(true)] out string? path)
        {
            var files = Directory.EnumerateFiles(BaseDirectory, "*.zip", SearchOption.AllDirectories);
            var file = files.FirstOrDefault();
            if (file is null) throw new KattekerCreatorException("Zip file not found.");
            ZipFile.ExtractToDirectory(file, BaseDirectory);
            return TryGetMakeNsisFilePath(out path);
        }

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