// Copyright © Selmo Technology GmbH. All Rights Reserved

namespace SelmoStudio.Hmi.Server.SelmoHmi.Sequence.Service
{
    public class StepService : IStepService
    {
        private List<(Guid, int)> _stepCounter = new();

        public event EventHandler CountChanged;

        public void DecrementStep(Guid id)
        {
            var found_item = GetStepCounter(id);
            found_item.Item2--;
            if (found_item.Item2 < 0)
                found_item.Item2 = 0;
            CountChanged.Invoke(this, EventArgs.Empty);
        }

        public int GetStepCount(Guid id)
        {
            var found_item = GetStepCounter(id);
            return found_item.Item2;
        }

        public void IncrementStep(Guid id)
        {
            var found_item = GetStepCounter(id);
            found_item.Item2++;
            CountChanged.Invoke(this, EventArgs.Empty);
        }

        private (Guid, int) GetStepCounter(Guid id)
        {
            var found = _stepCounter.Where(step => step.Item1 == id);
            if (!found.Any())
            {
                found = CreateStepCounter(id);
            }
            return found.First();
        }

        private IEnumerable<(Guid, int)> CreateStepCounter(Guid id)
        {
            _stepCounter.Add((id, 0));
            return _stepCounter.Where(step => step.Item1 == id);
        }

        public void ResetCount(Guid id)
        {
            var found_item = GetStepCounter(id);
            found_item.Item2 = 0;
            CountChanged.Invoke(this, EventArgs.Empty);
        }
    }
}