// WPFMA-SDK needs Unity 2022.3 (VRChat's version); on older Unity this file is skipped and WPFMAUnityVersionNotice explains why.
#if UNITY_2022_3_OR_NEWER
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using UnityEditor;
using UnityEngine;

namespace WPFMA
{
    /// <summary>
    /// Package safety: checks .unitypackages before they're imported, and catches risky scripts and DLLs that
    /// arrive any other way (double-clicking a package, copying files in) before Unity runs them. Anything held
    /// back goes to WPFMA-Quarantine next to Assets, where Unity can't load it, until the user says otherwise.
    /// </summary>
    [InitializeOnLoad]
    internal static class WPFMASafety
    {
        private const string GuardKey = "WPFMA.Safety.Guard";
        private const string HoldKey = "WPFMA.Safety.Hold";
        private const string TrustedKey = "WPFMA.Safety.Trusted";
        private const string KnownFile = "UserSettings/WPFMASafetyKnown.txt";
        internal const string QuarantineFolder = "WPFMA-Quarantine";

        private static readonly string[] Skipped = { "Assets/WPFMA-SDK/", "Assets/WPFMA-SDK-Dev/" };

        private static HashSet<string> trusted;
        private static HashSet<string> known;
        private static bool baselineRunning;

        // Background checks for the Import list.
        private static readonly Dictionary<string, SafetyReport> reports = new Dictionary<string, SafetyReport>(StringComparer.OrdinalIgnoreCase);
        private static readonly HashSet<string> scanning = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
        private static readonly object gate = new object();
        private static volatile bool changed;

        // Held back by the guard, waiting for the next editor tick.
        private static readonly List<QuarantinedFile> justHeld = new List<QuarantinedFile>();
        private static readonly List<SafetyItem> justNoticed = new List<SafetyItem>();
        private static bool finishQueued;
        private static readonly HashSet<string> checkedThisRound = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

        static WPFMASafety()
        {
            // Loaded here, on the main thread: background package checks ask IsTrusted, and EditorPrefs only works here.
            lock (gate)
                LoadTrusted();
            SafetyScanner.IsTrusted = IsTrusted;
            EditorApplication.update += Tick;
            EditorApplication.delayCall += StartBaseline;
        }

        // ---- Settings -------------------------------------------------------------------------------------------------

        /// <summary>Check new scripts and DLLs as they come into the project.</summary>
        internal static bool GuardOn
        {
            get { return EditorPrefs.GetBool(GuardKey, true); }
            set { EditorPrefs.SetBool(GuardKey, value); }
        }

        /// <summary>Hold back new DLLs and risky scripts (not just dangerous ones) until the user OKs them.</summary>
        internal static bool HoldRisky
        {
            get { return EditorPrefs.GetBool(HoldKey, true); }
            set { EditorPrefs.SetBool(HoldKey, value); }
        }

        /// <summary>Show each Import-list package's check result (checked in the background).</summary>
        internal static bool ListBadges
        {
            get { return EditorPrefs.GetBool("WPFMA.Safety.ListBadges", true); }
            set { EditorPrefs.SetBool("WPFMA.Safety.ListBadges", value); }
        }

        internal static string ProjectRoot
        {
            get { return Path.GetDirectoryName(Application.dataPath); }
        }

        internal static string QuarantineRoot
        {
            get { return Path.Combine(ProjectRoot, QuarantineFolder); }
        }

        // ---- Trusted files (by content, on this PC) ------------------------------------------------------------------

        internal static bool IsTrusted(string hash)
        {
            if (string.IsNullOrEmpty(hash))
                return false;
            lock (gate)
            {
                LoadTrusted();
                return trusted.Contains(hash);
            }
        }

        internal static void Trust(IEnumerable<string> hashes)
        {
            lock (gate)
            {
                LoadTrusted();
                foreach (var hash in hashes)
                    if (!string.IsNullOrEmpty(hash))
                        trusted.Add(hash);
                EditorPrefs.SetString(TrustedKey, string.Join("\n", trusted));
            }
            ForgetReports();
        }

        internal static int TrustedCount
        {
            get
            {
                lock (gate)
                {
                    LoadTrusted();
                    return trusted.Count;
                }
            }
        }

        internal static void ForgetTrusted()
        {
            lock (gate)
            {
                trusted = new HashSet<string>();
                EditorPrefs.DeleteKey(TrustedKey);
            }
            ForgetReports();
        }

        private static void LoadTrusted()
        {
            if (trusted != null)
                return;
            trusted = new HashSet<string>(EditorPrefs.GetString(TrustedKey, string.Empty)
                .Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries), StringComparer.OrdinalIgnoreCase);
        }

        // ---- Files already in this project when the guard first ran -------------------------------------------------

        private static string KnownPath
        {
            get { return Path.Combine(ProjectRoot, KnownFile); }
        }

        private static bool IsKnown(string hash)
        {
            return known != null && !string.IsNullOrEmpty(hash) && known.Contains(hash);
        }

        private static void AddKnown(IEnumerable<string> hashes)
        {
            if (known == null)
                known = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
            bool added = false;
            foreach (var hash in hashes)
                if (!string.IsNullOrEmpty(hash))
                    added |= known.Add(hash);
            if (!added)
                return;
            try
            {
                Directory.CreateDirectory(Path.GetDirectoryName(KnownPath));
                File.WriteAllLines(KnownPath, known.OrderBy(h => h));
            }
            catch (Exception e)
            {
                Debug.LogWarning("[WPFMA-SDK] Package safety: couldn't save " + KnownFile + ": " + e.Message);
            }
        }

        /// <summary>
        /// The first time the guard runs in a project, the DLLs already there are noted so they aren't held back as
        /// "new". Dangerous files are still reported.
        /// </summary>
        private static void StartBaseline()
        {
            if (known != null || baselineRunning)
                return;
            if (File.Exists(KnownPath))
            {
                known = new HashSet<string>(File.ReadAllLines(KnownPath).Where(l => l.Length > 0), StringComparer.OrdinalIgnoreCase);
                return;
            }

            baselineRunning = true;
            string root = ProjectRoot;
            var thread = new Thread(() =>
            {
                SafetyReport report = null;
                try
                {
                    report = SafetyScanner.ScanProject(root);
                }
                catch (Exception)
                {
                }

                EditorApplication.delayCall += () =>
                {
                    baselineRunning = false;
                    if (report == null)
                        return;
                    AddKnown(report.Items.Where(i => i.Level < SafetyLevel.Danger).Select(i => i.Hash));
                    if (!File.Exists(KnownPath))
                        AddKnown(new[] { "-" });
                    if (report.Level == SafetyLevel.Danger && !Application.isBatchMode)
                        WPFMASafetyWindow.ShowProject(report, "WPFMA-SDK found something dangerous already in this project.");
                };
            }) { IsBackground = true, Name = "WPFMA safety baseline" };
            thread.Start();
        }

        // ---- Checking packages in the background (for the Import list) ------------------------------------------------

        private static string Key(string path)
        {
            var info = new FileInfo(path);
            return info.Exists ? path + "|" + info.Length + "|" + info.LastWriteTimeUtc.Ticks : path;
        }

        /// <summary>The report for a package if it's been checked, else null (and a check starts in the background).</summary>
        internal static SafetyReport Cached(string packagePath)
        {
            string key = Key(packagePath);
            lock (gate)
            {
                SafetyReport report;
                if (reports.TryGetValue(key, out report))
                    return report;
                if (scanning.Contains(key) || scanning.Count >= 2)
                    return null;
                scanning.Add(key);
            }

            var thread = new Thread(() =>
            {
                var report = SafetyScanner.ScanPackage(packagePath);
                lock (gate)
                {
                    scanning.Remove(key);
                    reports[key] = report;
                }
                changed = true;
            }) { IsBackground = true, Name = "WPFMA package check", Priority = System.Threading.ThreadPriority.BelowNormal };
            thread.Start();
            return null;
        }

        private static void ForgetReports()
        {
            lock (gate)
                reports.Clear();
            changed = true;
        }

        /// <summary>Checks a package now (with a progress bar), using the background result if it's ready.</summary>
        internal static SafetyReport CheckNow(string packagePath)
        {
            string key = Key(packagePath);
            lock (gate)
            {
                SafetyReport cached;
                if (reports.TryGetValue(key, out cached))
                    return cached;
            }

            string name = Path.GetFileName(packagePath);
            try
            {
                var report = SafetyScanner.ScanPackage(packagePath, p => EditorUtility.DisplayProgressBar("Checking package", "Looking for DLLs and token loggers in " + name, p));
                lock (gate)
                    reports[key] = report;
                return report;
            }
            finally
            {
                EditorUtility.ClearProgressBar();
            }
        }

        /// <summary>Checks a project folder with a progress bar.</summary>
        internal static SafetyReport CheckProject()
        {
            try
            {
                return SafetyScanner.ScanProject(ProjectRoot, p => EditorUtility.DisplayProgressBar("Checking project", "Looking for DLLs and token loggers", p));
            }
            finally
            {
                EditorUtility.ClearProgressBar();
            }
        }

        // ---- Importing with a check first -----------------------------------------------------------------------------

        internal enum Choice
        {
            Import,
            ImportWithout,
            Cancel
        }

        /// <summary>
        /// Imports a package safely: what the check flags (anything dangerous, and new DLLs and risky scripts while
        /// "hold risky" is on) goes to WPFMA-Quarantine (never into Assets), and the rest imports as normal. Held
        /// files wait for Accept or Deny. finished(true) once an import has started.
        /// </summary>
        internal static void ImportChecked(string packagePath, bool interactive, Action<bool> finished)
        {
            var report = CheckNow(packagePath);
            if (report.Error != null)
            {
                // Couldn't look inside: show why, and let them decide.
                WPFMASafetyWindow.ShowPackage(report, choice =>
                {
                    bool started = ImportChoice(report, packagePath, interactive, choice);
                    if (finished != null)
                        finished(started);
                });
                return;
            }

            bool importing = SafeImport(report, packagePath, interactive);
            if (finished != null)
                finished(importing);
        }

        /// <summary>Carries out what the user picked in the report window. True if an import started.</summary>
        internal static bool ImportChoice(SafetyReport report, string packagePath, bool interactive, Choice choice)
        {
            if (choice == Choice.Cancel)
                return false;
            if (report.Error != null)
            {
                AssetDatabase.ImportPackage(packagePath, interactive);
                return true;
            }
            return SafeImport(report, packagePath, interactive);
        }

        /// <summary>
        /// Writes the flagged files (all of its code, if anything in it is dangerous) straight to quarantine, then
        /// imports a copy without them. Files that try to land outside the project are just left out. Otherwise
        /// scripts the check found nothing wrong with import with the rest:
        /// holding all of them back left packages that update their own code half old, half new (Poiyomi's new
        /// shaders arrived without the Thry Editor scripts they need, so the material editor broke).
        /// </summary>
        internal static bool SafeImport(SafetyReport report, string packagePath, bool interactive)
        {
            var code = report.Items.Where(i => !string.IsNullOrEmpty(i.Guid)).ToList();
            // A package with something dangerous in it: none of its code is trusted (its harmless-looking parts may
            // belong to the same malware).
            bool dangerous = report.Level == SafetyLevel.Danger;
            var hold = code.Where(i => i.Kind != SafetyScanner.KindPath && (dangerous ? !i.Trusted : ShouldHold(i))).ToList();
            var leaveOut = new HashSet<string>(code.Where(i => i.Kind == SafetyScanner.KindPath).Select(i => i.Guid));
            leaveOut.UnionWith(hold.Select(i => i.Guid));
            if (leaveOut.Count == 0)
            {
                AssetDatabase.ImportPackage(packagePath, interactive);
                return true;
            }

            string package = Path.GetFileNameWithoutExtension(packagePath);
            string batch = Path.Combine(QuarantineRoot, DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss") + " " + WPFMAPaths.SafeFileName(package));
            string folder = Path.Combine(ProjectRoot, "Library", "WPFMASafety");
            string copy = Path.Combine(folder, package + " (without code).unitypackage");
            try
            {
                EditorUtility.DisplayProgressBar("Safe import", "Holding back the scripts and DLLs", 0.3f);
                if (hold.Count > 0)
                {
                    SafetyScanner.Extract(packagePath, hold.ToDictionary(i => i.Guid, i => i.Path), batch);
                    foreach (var item in hold)
                        new QuarantinedFile { Original = item.Path, Stored = Path.Combine(batch, item.Path), Item = item, Source = package }.Save();
                }

                EditorUtility.DisplayProgressBar("Safe import", "Making a copy without them", 0.6f);
                Directory.CreateDirectory(folder);
                SafetyScanner.WriteWithout(packagePath, leaveOut, copy);
            }
            catch (Exception e)
            {
                EditorUtility.DisplayDialog("Safe import", "Couldn't prepare " + package + ":\n" + e.Message + "\n\nNothing was imported.", "OK");
                return false;
            }
            finally
            {
                EditorUtility.ClearProgressBar();
            }

            Debug.Log("[WPFMA-SDK] Safe import: " + package + " imported; " + hold.Count + " flagged file(s) wait in " + QuarantineFolder + ".");
            // Only code in it: nothing left to import.
            if (report.Files > leaveOut.Count)
                AssetDatabase.ImportPackage(copy, interactive);
            if (hold.Count > 0 && !Application.isBatchMode)
                EditorApplication.delayCall += () => WPFMASafetyWindow.ShowQuarantine();
            return true;
        }

        /// <summary>
        /// The same rule as for files that arrive any other way: dangerous files always, and DLLs and risky scripts
        /// you haven't OK'd before while "hold risky" is on. Clean scripts never.
        /// </summary>
        private static bool ShouldHold(SafetyItem item)
        {
            if (item.Level == SafetyLevel.Danger)
                return true;
            return HoldRisky && item.Shown >= SafetyLevel.Check && item.RunsInUnity && !IsKnown(item.Hash);
        }

        // ---- The guard: files that just arrived -----------------------------------------------------------------------

        private sealed class Guard : AssetPostprocessor
        {
            private static void OnPostprocessAllAssets(string[] imported, string[] deleted, string[] moved, string[] movedFrom)
            {
                if (GuardOn && imported.Length > 0)
                    CheckArrivals(imported);
            }
        }

        /// <summary>Checks newly imported files. Called while Unity is importing, before it compiles or loads them.</summary>
        internal static void CheckArrivals(IEnumerable<string> imported)
        {
            string root = ProjectRoot;
            var flagged = new List<SafetyItem>();
            foreach (var path in imported)
            {
                if (!path.StartsWith("Assets/", StringComparison.Ordinal) || Skipped.Any(s => path.StartsWith(s, StringComparison.OrdinalIgnoreCase)))
                    continue;
                if (path.Split('/').Any(part => part.EndsWith("~", StringComparison.Ordinal) || part.StartsWith(".", StringComparison.Ordinal)))
                    continue;
                string full = Path.Combine(root, path);
                if (!File.Exists(full))
                    continue;
                if (!checkedThisRound.Add(path + "|" + File.GetLastWriteTimeUtc(full).Ticks))
                    continue;
                var item = SafetyScanner.ScanDiskFile(full, path);
                if (item != null && item.Shown >= SafetyLevel.Check)
                    flagged.Add(item);
            }
            if (flagged.Count == 0)
                return;

            bool firstRun = known == null && !File.Exists(KnownPath);
            if (known == null && !firstRun)
                StartBaseline();

            var hold = new List<SafetyItem>();
            var notice = new List<SafetyItem>();
            foreach (var item in flagged)
            {
                bool seen = IsKnown(item.Hash);
                if (item.Level == SafetyLevel.Danger)
                    hold.Add(item);
                else if (seen || firstRun)
                    continue;
                else if (HoldRisky && item.RunsInUnity && !WPFMA.Team.TeamFiles.JustWrote(item.Path))
                    hold.Add(item);
                else
                    notice.Add(item);
            }
            if (firstRun)
                AddKnown(flagged.Where(i => i.Level < SafetyLevel.Danger).Select(i => i.Hash));

            if (hold.Count > 0)
                Quarantine(hold);
            if (hold.Count > 0 || notice.Count > 0)
            {
                lock (gate)
                    justNoticed.AddRange(notice);
                AddKnown(notice.Select(i => i.Hash));
                QueueFinish();
            }
        }

        /// <summary>Moves files (and their .meta) to WPFMA-Quarantine, outside Assets, until the user accepts or denies them.</summary>
        private static void Quarantine(List<SafetyItem> items)
        {
            string batch = Path.Combine(QuarantineRoot, DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss"));
            foreach (var item in items)
            {
                string from = Path.Combine(ProjectRoot, item.Path);
                string to = Path.Combine(batch, item.Path);
                try
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(to));
                    File.Move(from, to);
                    if (File.Exists(from + ".meta"))
                        File.Move(from + ".meta", to + ".meta");
                    var held = new QuarantinedFile { Original = item.Path, Stored = to, Item = item };
                    held.Save();
                    lock (gate)
                        justHeld.Add(held);
                    Debug.LogWarning("[WPFMA-SDK] Package safety held back " + item.Path + ": " + item.Summary + ". It's in " +
                                     QuarantineFolder + " until you decide.");
                }
                catch (Exception e)
                {
                    Debug.LogError("[WPFMA-SDK] Package safety couldn't move " + item.Path + " out of the project (" + e.Message +
                                   "). Delete it yourself: " + item.Summary);
                }
            }
        }

        private static void QueueFinish()
        {
            if (finishQueued)
                return;
            finishQueued = true;
            EditorApplication.delayCall += FinishPending;
        }

        /// <summary>After the import: refresh so Unity forgets the moved files, then show them to accept or deny.</summary>
        internal static void FinishPending()
        {
            finishQueued = false;
            List<QuarantinedFile> held;
            List<SafetyItem> noticed;
            lock (gate)
            {
                held = justHeld.ToList();
                noticed = justNoticed.ToList();
                justHeld.Clear();
                justNoticed.Clear();
            }

            checkedThisRound.Clear();
            if (held.Count > 0)
                AssetDatabase.Refresh();

            if ((held.Count > 0 || noticed.Count > 0) && !Application.isBatchMode)
                WPFMASafetyWindow.ShowArrivals(held, noticed);
        }

        private static void Tick()
        {
            // In case the delayed call was lost.
            if (finishQueued && !EditorApplication.isUpdating && !EditorApplication.isCompiling)
                FinishPending();

            if (!changed)
                return;
            changed = false;
            foreach (var window in Resources.FindObjectsOfTypeAll<WPFMAWindow>())
                window.Repaint();
        }

        // ---- What's in quarantine -------------------------------------------------------------------------------------

        internal static List<QuarantinedFile> Quarantined()
        {
            var list = new List<QuarantinedFile>();
            if (!Directory.Exists(QuarantineRoot))
                return list;
            foreach (var info in Directory.GetFiles(QuarantineRoot, "*" + QuarantinedFile.InfoSuffix, SearchOption.AllDirectories))
            {
                var file = QuarantinedFile.Load(info);
                if (file != null)
                    list.Add(file);
            }
            return list.OrderByDescending(f => f.Stored).ToList();
        }

        internal static bool PutBack(QuarantinedFile file)
        {
            return Accept(new[] { file }) == 1;
        }

        /// <summary>Moves files back into Assets and trusts them, with one refresh at the end. Returns how many moved.</summary>
        internal static int Accept(IEnumerable<QuarantinedFile> files)
        {
            int moved = 0, alreadyThere = 0;
            var problems = new List<string>();
            foreach (var file in files.ToList())
            {
                string to = Path.Combine(ProjectRoot, file.Original);
                if (File.Exists(to))
                {
                    // The same file is already in the project (say, a package that came with Gesture Manager when
                    // the project has it already): nothing to put back, so the held copy just goes.
                    if (SameFile(to, file.Stored))
                    {
                        try
                        {
                            if (!string.IsNullOrEmpty(file.Hash))
                                Trust(new[] { file.Hash });
                            File.Delete(file.Stored);
                            if (File.Exists(file.Stored + ".meta"))
                                File.Delete(file.Stored + ".meta");
                            file.Forget();
                            alreadyThere++;
                        }
                        catch (Exception e)
                        {
                            problems.Add(file.Original + " (" + e.Message + ")");
                        }
                        continue;
                    }
                    problems.Add(file.Original + " (a different file is already there)");
                    continue;
                }
                try
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(to));
                    if (!string.IsNullOrEmpty(file.Hash))
                        Trust(new[] { file.Hash });
                    File.Move(file.Stored, to);
                    if (File.Exists(file.Stored + ".meta"))
                        File.Move(file.Stored + ".meta", to + ".meta");
                    file.Forget();
                    moved++;
                }
                catch (Exception e)
                {
                    problems.Add(file.Original + " (" + e.Message + ")");
                }
            }

            RemoveEmptyFolders(QuarantineRoot);
            if (moved > 0)
                AssetDatabase.Refresh();
            if (moved + alreadyThere > 0)
                Debug.Log("[WPFMA-SDK] Package safety: accepted " + (moved + alreadyThere) + " file(s)" +
                          (alreadyThere > 0 ? " (" + alreadyThere + " were already in the project, so their held copies were cleared)." : "."));
            if (problems.Count > 0)
                EditorUtility.DisplayDialog("Package safety", "Couldn't accept " + problems.Count + " file(s):\n" + string.Join("\n", problems.Take(10)) +
                                                              (problems.Count > 10 ? "\n..." : string.Empty), "OK");
            return moved + alreadyThere;
        }

        private static bool SameFile(string a, string b)
        {
            try
            {
                var ia = new FileInfo(a);
                var ib = new FileInfo(b);
                if (!ib.Exists || ia.Length != ib.Length)
                    return false;
                using (var md5 = System.Security.Cryptography.MD5.Create())
                {
                    byte[] ha, hb;
                    using (var s = File.OpenRead(a))
                        ha = md5.ComputeHash(s);
                    using (var s = File.OpenRead(b))
                        hb = md5.ComputeHash(s);
                    return ha.SequenceEqual(hb);
                }
            }
            catch (Exception)
            {
                return false;
            }
        }

        internal static void Deny(IEnumerable<QuarantinedFile> files)
        {
            foreach (var file in files.ToList())
                Delete(file);
        }

        internal static void Delete(QuarantinedFile file)
        {
            try
            {
                File.Delete(file.Stored);
                if (File.Exists(file.Stored + ".meta"))
                    File.Delete(file.Stored + ".meta");
                file.Forget();
                RemoveEmptyFolders(QuarantineRoot);
            }
            catch (Exception e)
            {
                Debug.LogWarning("[WPFMA-SDK] Package safety couldn't delete " + file.Stored + ": " + e.Message);
            }
        }

        private static void RemoveEmptyFolders(string folder)
        {
            if (!Directory.Exists(folder))
                return;
            foreach (var sub in Directory.GetDirectories(folder))
                RemoveEmptyFolders(sub);
            if (!Directory.EnumerateFileSystemEntries(folder).Any())
                Directory.Delete(folder);
        }

        internal static void OpenQuarantineFolder()
        {
            Directory.CreateDirectory(QuarantineRoot);
            EditorUtility.RevealInFinder(QuarantineRoot);
        }
    }

    /// <summary>A file held in WPFMA-Quarantine, with a small note next to it saying where it came from and why.</summary>
    internal sealed class QuarantinedFile
    {
        internal const string InfoSuffix = ".wpfma-held.txt";

        public string Original;
        public string Stored;
        public string Hash;
        public string Kind;
        public string Level;
        public string Summary;
        public string Source;
        public SafetyItem Item;
        public readonly List<string> Reasons = new List<string>();

        private string InfoPath
        {
            get { return Stored + InfoSuffix; }
        }

        public void Save()
        {
            if (Item != null)
            {
                Hash = Item.Hash;
                Kind = Item.Kind;
                Level = Item.Level.ToString();
                Summary = Item.Summary;
            }
            var lines = new List<string>
            {
                "WPFMA-SDK held this file back so Unity couldn't run it.",
                "original: " + Original,
                "kind: " + Kind,
                "level: " + Level,
                "why: " + Summary,
                "sha256: " + Hash,
                "source: " + (Source ?? "Arrived in the project"),
                "held: " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
            };
            if (Item != null)
                lines.AddRange(Item.Reasons.Select(r => "- " + r.Level + ": " + r.Text + (r.Evidence != null ? "  [" + r.Evidence + "]" : string.Empty)));
            File.WriteAllLines(InfoPath, lines);
        }

        public static QuarantinedFile Load(string infoPath)
        {
            try
            {
                string stored = infoPath.Substring(0, infoPath.Length - InfoSuffix.Length);
                if (!File.Exists(stored))
                    return null;
                var file = new QuarantinedFile { Stored = stored };
                foreach (var line in File.ReadAllLines(infoPath))
                {
                    if (line.StartsWith("- ", StringComparison.Ordinal))
                    {
                        file.Reasons.Add(line.Substring(2));
                        continue;
                    }
                    int colon = line.IndexOf(": ", StringComparison.Ordinal);
                    if (colon <= 0)
                        continue;
                    string value = line.Substring(colon + 2);
                    switch (line.Substring(0, colon))
                    {
                        case "original": file.Original = value; break;
                        case "kind": file.Kind = value; break;
                        case "level": file.Level = value; break;
                        case "why": file.Summary = value; break;
                        case "sha256": file.Hash = value; break;
                        case "source": file.Source = value; break;
                    }
                }
                return file.Original != null ? file : null;
            }
            catch (Exception)
            {
                return null;
            }
        }

        public void Forget()
        {
            try
            {
                if (File.Exists(InfoPath))
                    File.Delete(InfoPath);
            }
            catch (Exception)
            {
            }
        }

        public bool IsDanger
        {
            get { return Level == SafetyLevel.Danger.ToString(); }
        }
    }
}
#endif
