// 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 System;
using Hiperscan.Common;

namespace Hiperscan.ApoIdentCore.ComplexFinder
{
    public class RecalibrationTimer : Polling
    {
        public event EventHandler TimeUpdated = null;
        public event EventHandler TimerCycleFinished = null;

        public RecalibrationTimer()
        {
            this.PollingTimeIntervallMilliSeconds = 340;
            this.WaitTimeMilliSeconds = 170;
        }

        protected override void BeforeStartRunning()
        {
            this.EndTime = this.RecalibrationTimeStamp.AddMilliseconds(this.RecalibrationTimeoutMilliSeconds);
        }

        protected override void AfterFinishRunning()
        {
            this.EndTime = DateTime.Now.AddYears(-1);
        }

        protected override void ExecutePollingEvent()
        {
            this.UpdateTime();
            this.TimeUpdated?.Invoke(this, EventArgs.Empty);
        }

        public void UpdateTime()
        {   
            DateTime now = DateTime.Now;
            if (now > this.EndTime)
            {
                this.TimeLeft = "00:00 min";
                this.TimerCycleFinished?.Invoke(this, EventArgs.Empty);
                this.StopPolling();
            }
            else
            {
                TimeSpan diff = this.EndTime - now;
                this.TimeLeft = String.Format("{0:D2}:{1:D2} min",
                                              diff.Minutes,
                                              diff.Seconds);
            }
        }

        private DateTime EndTime { get; set; }
        public uint RecalibrationTimeoutMilliSeconds { get; set; }
        public DateTime RecalibrationTimeStamp { get; set; }
        public string TimeLeft { get; private set; } = String.Empty;
    }
}
