using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Katteker.AppStub
{
    internal class Program
    {
        private Program()
        {
            CurrentDir = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory);
            ConfigFile = new IniFile(Path.Combine(CurrentDir.FullName, "app.ini"));
        }

        private DirectoryInfo CurrentDir { get; }

        private IniFile ConfigFile { get; }

        private Process MainProcess { get; set; }

        [STAThread]
        private static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            var p = new Program();
            p.Run(args);
        }

        private void Run(string[] args)
        {
            StartExecutable(args);
            StartUpdateInfo();
        }

        private static void StartUpdateInfo()
        {
            Application.Run(new InstallerUx("TestProgramm"));
        }

        private void StartExecutable(string[] args)
        {
            var dirEntries = CurrentDir.EnumerateDirectories().Where(x => x.Name.StartsWith("app-"))
                .Select(x => new AppEntry(x)).ToList();

            var latestVersion = dirEntries.OrderByDescending(x => x).FirstOrDefault();

            if (latestVersion != null && ConfigFile.Exists)
            {
                try
                {
                    var executable = ConfigFile.Read("Executable", "Main");

                    var a = args.Aggregate(string.Empty, (current, s) => current + s + " ").TrimEnd(' ');
                    MainProcess = new Process
                    {
                        StartInfo =
                            new ProcessStartInfo($"{latestVersion.DirInfo.FullName}\\{executable}")
                            {
                                Arguments = a,
                                WorkingDirectory = latestVersion.DirInfo.FullName,
                                UseShellExecute = false
                            }
                    };
                    MainProcess.Start();
                    Task.Run(() =>
                        DeleteOldVersionDirectories(dirEntries.Where(x =>
                            x.DirInfo.Name != latestVersion.DirInfo.Name)));
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                MessageBox.Show("Error, File not found", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private static void DeleteOldVersionDirectories(IEnumerable<AppEntry> dirEntries)
        {
#if !DEBUG
            foreach (var directoryInfo in dirEntries)
            {
                try
                {
                    directoryInfo.DirInfo.Delete(true);
                }
                catch (Exception)
                {
                    // silently ignore
                }
            }
#endif
        }
    }
}