// Created with MonoDevelop
//
//    QuickStep: Acquire, view and identify spectra 
//    Copyright (C) 2022, 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 Hiperscan.GuiExtensions.Dialog;

namespace Hiperscan.GuiExtensions
{
    public abstract class SyncControlTemplate<T,U> where T : UpdateArgsTemplate<U> where U : DialogArgsTempleate
    {
        public void EnterUpdateGui(T args)
        {
            lock (this.GuiUpdateAccessSync)
            {
                args.IsUpdating = true;
                this.RunActionByEnter(args);
            }
        }

        public void LeaveUpdateGui(T args)
        {
            lock (this.GuiUpdateAccessSync)
            {
                args.IsUpdating = false;
            }
        }

        public void WaitForUpdateGuiFinished(T args)
        {
            for (; ; )
            {
                lock (this.GuiUpdateAccessSync)
                {
                    if (args.IsUpdating == false)
                    {
                        this.RunActionByLeave(args);
                        break;
                    }
                }

                System.Threading.Thread.Sleep(this.WaitTimeMilliSeconds);
            }
        }

        protected abstract void RunActionByEnter(T args);
        protected abstract void RunActionByLeave(T args);
       

        public int WaitTimeMilliSeconds { get; set; } = 10;
        private object GuiUpdateAccessSync { get; set; } = new object();

    }
}
