using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Windows.Forms;
using Semver;

namespace AppStub
{
    internal static class Program
    {
        [STAThread]
        private static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            try
            {
                var commandline = string.Join(" ", args);
                var location = new FileInfo(Assembly.GetExecutingAssembly().Location);
                var directory = location.Directory;
                if (directory == null) return;
                var files = directory.EnumerateFiles(location.Name, SearchOption.AllDirectories)
                    .Where(x => x.Directory?.Name.StartsWith("app-") == true);

                var entries = new SortedList<SemVersion, FileInfo>();

                foreach (var file in files)
                {
                    var version = SemVersion.TryParse(file.Directory?.Name.Replace("app-", ""), out var value)
                        ? value
                        : new SemVersion(0);
                    entries.Add(version, file);
                }

                var latestVersion = entries.LastOrDefault().Value;
                if (latestVersion == null) throw new FileNotFoundException();
                DeleteOldVersionDirectories(entries.Where(x => x.Value != latestVersion));
                using (var process = new Process())
                {
                    process.StartInfo =
                        new ProcessStartInfo(latestVersion.FullName)
                        {
                            Arguments = commandline,
                            WorkingDirectory = latestVersion.DirectoryName ?? Assembly.GetExecutingAssembly().Location,
                            UseShellExecute = false
                        };
                    process.Start();
                    process.WaitForExit();
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private static void DeleteOldVersionDirectories(IEnumerable<KeyValuePair<SemVersion, FileInfo>> dirEntries)
        {
            if (Debugger.IsAttached) return;
            foreach (var directoryInfo in dirEntries)
            {
                try
                {
                    directoryInfo.Value.Directory?.Delete(true);
                }
                catch
                {
                    // silently ignore
                }
            }
        }
    }
}