using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace AVS
{
    class Updater
    {
        public string SVNversion;
        public string Softwareversion;
        SoftwareVersionUtility SoftwareVersionUtility = new SoftwareVersionUtility();

        public async Task CheckVersionAsync()
        {
            // Read version from SVN
            SVNversion = await SoftwareVersionUtility.CheckVersion();

            // Assembly version in properties
            Softwareversion = Assembly.GetExecutingAssembly().GetName().Version.ToString();

            // If versions are different, trigger the update
            if (SVNversion != Softwareversion)
            {
 
                DialogResult dialogResult = MessageBox.Show("A new version is available. Do you want to update now?",
                    "Update Available", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                if (dialogResult == DialogResult.Yes)
                {
                    // Start the update process
                    await StartUpdateProcessAsync();
                }
                else
                {
                 // retries update if user does not want to update in 5 minutes
                    await Task.Delay(TimeSpan.FromSeconds(300));
                    await StartUpdateProcessAsync();
                }

            }
        }

        public async Task StartUpdateProcessAsync()
        {
            try
            {
                string updaterPath = "C:\\Users\\Public\\Documents\\AVS\\AVSUpdater.exe";

               
                // Start the updater process
                ProcessStartInfo processStartInfo = new ProcessStartInfo
                {
                    FileName = updaterPath,
                    //Arguments = $"\"{sourcePath}\" \"{destinationPath}\"",
                    UseShellExecute = false,
                    //CreateNoWindow = true,
                };

                Process.Start(processStartInfo);

                // Close the current application
                //await Task.Delay(1000); // Delay to allow the updater to initialize
               
                Environment.Exit(0);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Failed to start the update process: {ex.Message}", "Update Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}