// Created with MonoDevelop
//
//    QuickStep: Acquire, view and identify spectra 
//    Copyright (C) 2021 Hiperscan GmbH Dresden, Germany
//
//    This program is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    This program is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with this program.  If not, see <http://www.gnu.org/licenses/>.




using System;
using Hiperscan.ApoIdentCommon;
using Hiperscan.Unix;

namespace Hiperscan.ApoIdentCore.SoftwareUpgrade
{
    public class SoftwareUpgradeRaspian
    {
        public EventHandler OnError = null;

        public SoftwareUpgradeRaspian(bool is_active)
        {
            this.CanRun = is_active;
        }

        public void Run()
        {
            if (this.CanRun == false)
                return;

            System.Threading.Tasks.Task.Run(() =>
            {
                try
                {
                    if (SoftwareUpgradeRaspian.CurrentProc != null)
                        return;

                    System.Diagnostics.Process proc = new System.Diagnostics.Process();
                    proc.StartInfo.FileName = "xterm";
                    proc.StartInfo.Arguments = String.Format("-e \"{0}\"", GlobalFiles.ApoIdentRaspianUpdateScript);
                    proc.StartInfo.UseShellExecute = true;
                    proc.StartInfo.CreateNoWindow = false;

                    SoftwareUpgradeRaspian.CurrentProc = proc;
                    proc.Start();
                    proc.WaitForExit();

                    if (proc.ExitCode != 0)
                    {
                        string message = String.Format(Catalog.GetString("Process finished with error code: {0}."),
                                                       proc.ExitCode);

                        throw new Exception(message);
                    }

                    SoftwareUpgradeRaspian.CurrentProc = null;
                }
                catch (Exception ex)
                {
                    SoftwareUpgradeRaspian.CurrentProc = null;
                    this.Exception = ex;
                    this.OnError?.Invoke(this, EventArgs.Empty);
                }
            });
        }



        private bool CanRun { get; set; }
        public Exception Exception { get; private set; } = null;

        private static System.Diagnostics.Process CurrentProc { get; set; }
    }
}
