using System;
using System.IO;
using System.Threading;

namespace KattekerCreator.Types
{
    public class TemporaryDirectory : IDisposable
    {
        public string Path { get; }

        public TemporaryDirectory(string path)
        {
            Path = path;
        }

        void IDisposable.Dispose()
        {
            try
            {
                Thread.Sleep(100);
                Directory.Delete(Path, true);
            }
            catch
            {
                //Try it, catch it, forget it.
            }
        }

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

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