using VisionBuilder.UI.Common;
using VisionBuilder.UI.Common.ViewModel;
using VisionBuilder.UI.IOCommander.Settings;

namespace VisionBuilder.UI.IOCommander.Modules;

public class IOCommanderProgramModule: IVisionBuilderModule
{
    private readonly IOCommanderSettings _settings;
    private readonly IOCommanderModule _mainModule;
    private readonly MainWindowVM _mainWindowVm;

    public IOCommanderProgramModule(IOCommanderSettings settings, IOCommanderModule mainModule, MainWindowVM mainWindowVm)
    {
        _settings = settings;
        _mainModule = mainModule;
        _mainWindowVm = mainWindowVm;
        _mainWindowVm.ProgramStarted += _mainWindowVm_ProgramStarted;
        _mainWindowVm.ProgramClosed += _mainWindowVm_ProgramClosed;
    }

    private void EmitEvent(EProcessingEvent @event)
    {
        var actions = _settings.GlobalEvents.First(x => x.Event == @event);
        foreach (var action in actions.Actions)
        {
            _mainModule.SetOutput(action.Pin,!action.Low);
            if (action.Pulse)
            {
                Task.Run(async () =>
                {
                    await Task.Delay(_settings.PulseLength);
                    _mainModule.SetOutput(action.Pin, action.Low);
                });
            }
        }
    }


    private void _mainWindowVm_ProgramClosed()
    {
        EmitEvent(EProcessingEvent.ProgramEnded);
    }


    private void _mainWindowVm_ProgramStarted()
    {
        EmitEvent(EProcessingEvent.ProgramStarted);
    }

    public void InitializeModule()
    {
        
    }
}