// Copyright © Selmo Technology GmbH. All Rights Reserved

using Novus.Connectivity.Common;
using SelmoStudio.Hmi.Server.ProcessValue.Services;
using SelmoStudio.Hmi.Server.SelmoHmi.Shared.Component;
using SelmoStudio.Hmi.Server.SelmoHmi.Shared.TestImpl;

namespace SelmoStudio.Hmi.Server.Shared.Service
{
    public class SelmoHmiValueHandler
    {
        private IProcessValuePollingService _valuePollingService;
        private SemaphoreSlim _lock;

        public SelmoHmiValueHandler(IProcessValuePollingService valuePollingService)
        {
            _lock = new SemaphoreSlim(1);
            _valuePollingService = valuePollingService;
        }

        internal async Task HandleEvent(ComponentEventArgs e)
        {
            try
            {
                await _lock.WaitAsync();

                foreach (var pvHandleInfo in e.ProcessInfo.ProcessValueHandleInfos)
                {
                    var pv = pvHandleInfo.ProcessValueInfo;

                    var valueHandle = pvHandleInfo.ProcessValueHandle;
                    await _valuePollingService.WriteValue(CreateProcessValue(pvHandleInfo));
                    //if (valueHandle == ProcessValueHandle.TextInput )
                    //{
                    //    await _valuePollingService.WriteValue(CreateProcessValue(pvhandleInfo));
                    //}
                    //if (valueHandle == ProcessValueHandle.Switch)
                    //{
                    //    await _valuePollingService.WriteValue(CreateProcessValue(pvhandleInfo));
                    //}

                    //Task.Delay(_cycleTime)
                }
            }
            catch (Exception ex)
            {
                // TODO some error handling
            }
            finally
            {
                _lock.Release();
            }
        }

        private IProcessValue CreateProcessValue(ProcessValueHandleInfo pvhandleInfo)
        {
            var pv = new TestValuesForDemo.TestProcessValue()
            {
                Value = pvhandleInfo.Value,
                ValueInfo = pvhandleInfo.ProcessValueInfo
            };

            return pv;
        }
    }
}