using SupportClasses;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace DataClients
{
  public static class TempDir
  {
    private static readonly char split = _Directory.Slash;
    private static string dir = Directory.GetCurrentDirectory() + split + "temp";
    private static List<string> protect = new List<string>();
    private static Task checkTask = null;
    private static async Task CheckDir()
		{
      while (true)
      {
        Directory.CreateDirectory(dir);
        var listFiles = Directory.GetFiles(dir);
        foreach (var e in listFiles)
        {
          var name = e.Split(split).Last();
          if (!protect.Contains(name) && File.GetCreationTime(e) < DateTime.Now.AddMinutes(-5))
            File.Delete(e);
        }
        await Task.Delay(5 * 60 * 1000);
      }
    }
    public static void StartCkeckDir()
		{
      if (checkTask == null)
        checkTask = Task.Run(() => CheckDir());
		}
    public static bool AddProtect(string name)
		{
      StartCkeckDir();
      if (!protect.Contains(name))
      {
        protect.Add(name);
        return true;
      }
      return false;
		}
    public static bool RemoveProtect(string name)
		{
      StartCkeckDir();
      if (protect.Contains(name))
      {
        protect.Remove(name);
        return true;
      }
      return false;
		}
    public static string GetTempDirectory()
		{
      StartCkeckDir();
      return dir;
		}
    public static bool IsProtect(string name)
		{
      StartCkeckDir();
      return protect.Contains(name);
		}
    public static bool IsExist(string name)
    {
      StartCkeckDir();
      if (File.Exists(dir + split + name))
        if (File.GetCreationTime(dir + split + name) > DateTime.Now.AddMinutes(-5))
          return true;
        else
          File.Delete(dir + split + name);
      return false;
    }

  }
}
