using System;
using System.IO;
using KattekerCreator.Helper;

namespace KattekerCreator.Types
{
    public readonly struct TemporaryDirectory : IDisposable
    {
        private readonly DirectoryInfo _directoryInfo;

        private TemporaryDirectory(DirectoryInfo path)
        {
            _directoryInfo = path ?? throw new ArgumentNullException(nameof(path));
        }

        void IDisposable.Dispose() => Utils.TryDeleteDirectory(_directoryInfo, 100);

        public string Path => _directoryInfo.FullName;

        public static TemporaryDirectory Create()
        {
            string result;
            do
            {
                result = System.IO.Path.Combine(Utils.BaseDirectory, "temp", Environment.UserName,
                    System.IO.Path.GetRandomFileName());
            } while (Directory.Exists(result));

            return new TemporaryDirectory(Directory.CreateDirectory(result));
        }
    }
}