using Avalonia.Threading;
using DaireApplication.Views;
using System;
using System.Linq;
using System.Threading.Tasks;

namespace DaireApplication.Loops;

public class ScreenLoop
{
    static void SetBrightness(int value)
    {
        //File.WriteAllText("/sys/class/backlight/backlight/brightness", value.ToString());
    }
    public static async void Screen(MainWindow _mainWindow)
    {
        var screenData = _mainWindow._screeen.ReadScreens()?[0];
        SetBrightness((int)(screenData.brightness / 100 * 255));
        while (true)
        {
            try
            {
                screenData = _mainWindow._screeen.ReadScreens()?[0];

                if ((DateTime.Now - _mainWindow.lastActivity).TotalSeconds >= screenData?.offSec)
                {
                    if (!MainWindow.isOff)
                    {
                        MainWindow.isOff = true;
                        SetBrightness(0);
                    }

                }
                else if ((DateTime.Now - _mainWindow.lastActivity).TotalSeconds >= screenData?.dimSec)
                {
                    MainWindow.isOff = false;
                    SetBrightness(51); // 20% of 255
                }

                if (MainWindow.errors.Count > 0)
                {
                    foreach (var item in MainWindow.errors.ToList())
                    {

                        if ((DateTime.Now - item.errorDate).TotalSeconds >= 2.5)
                        {
                            if (!item.isShowen)
                            {
                                Dispatcher.UIThread.Post(() =>
                                {
                                    if (_mainWindow.errorMsg.Text.Contains($"- {item.GetDisplayNames(item.Condition)}"))
                                    {
                                        item.isShowen = true;

                                    }
                                    else
                                    {
                                        _mainWindow.errorMsg.Text += $"\n- {item.GetDisplayNames(item.Condition)}";
                                        item.isShowen = true;
                                    }

                                });
                            }
                            if (item.isDeleted)
                            {
                                Dispatcher.UIThread.Post(() =>
                                {
                                    _mainWindow.errorMsg.Text = _mainWindow.errorMsg.Text
                                    .Replace($"- {item.GetDisplayNames(item.Condition)}", "");
                                    MainWindow.errors.Remove(item);
                                });
                            }

                            Dispatcher.UIThread.Post(() =>
                            {
                                _mainWindow.errorMsg.Text = _mainWindow.errorMsg.Text.Trim();
                                if (_mainWindow.ContentArea.Content is Settings settings && MainWindow.errors.Count > 0)
                                {
                                    //_mainWindow.footerMsg.Text = "";
                                    settings.mixerBtn.IsEnabled = false;
                                    settings.fountainBtn.IsEnabled = false;
                                    settings.moldHeaterBtn.IsEnabled = false;
                                    settings.vibrationBtn.IsEnabled = false;
                                    settings.vibHeaterBtn.IsEnabled = false;
                                    _mainWindow.PreHeatingBtn.IsEnabled = false;
                                    //_mainWindow.recipeStartBtn.IsEnabled = false;
                                }
                            });

                        }
                    }

                    if (MainWindow.errors.Count > 0)
                    {
                        if ((DateTime.Now - MainWindow.errors.Min(x => x.errorDate)).TotalSeconds >= 3.5)
                        {
                            Dispatcher.UIThread.Post(() =>
                            {
                                _mainWindow.errorLogo.IsVisible = true;

                                _mainWindow.errorTitel.Text = $"Error Number: {MainWindow.errors.Count}";
                                _mainWindow.errorMsg.Text = _mainWindow.errorMsg.Text.Trim();

                                //_mainWindow.footerMsg.Text = $"Error Numbers: {MainWindow.errors.Count}";
                                //_mainWindow.errorLogoBtn.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
                            });
                        }


                    }

                }
                else
                {
                    Dispatcher.UIThread.Post(() =>
                    {

                        //MainWindow.errors.Clear();
                        _mainWindow.errorLogo.IsVisible = false;
                        _mainWindow.errorPopupOverlay.IsVisible = false;
                        if (_mainWindow.ContentArea.Content is Settings settings)
                        {
                            //_mainWindow.footerMsg.Text = "Ready";
                           
                            settings.moldHeaterBtn.IsEnabled = true;
                            settings.vibrationBtn.IsEnabled = true;
                            settings.vibHeaterBtn.IsEnabled = true;
                            _mainWindow.recipeStartBtn.IsEnabled = true;
                            if (_mainWindow.startRecipe != 1)
                            {
                                _mainWindow.PreHeatingBtn.IsEnabled = true;
                                settings.mixerBtn.IsEnabled = true;
                                settings.fountainBtn.IsEnabled = true;

                            }
                            var isFountOn = false;
                            var isMixerOn = false;
                            var fountainMotor =_mainWindow._mapping.Find(x => x.Name.ToLower() == "Helix".ToLower());
                            var mixerMotor =_mainWindow._mapping.Find(x => x.Name.ToLower() == "Mixer".ToLower());
                            if (isFountOn !=fountainMotor.BitNumbers.All(bit => (_mainWindow.holdingRegister.motor & (1 << bit)) != 0))
                            {
                                isFountOn = fountainMotor.BitNumbers.All(bit => (_mainWindow.holdingRegister.motor & (1 << bit)) != 0);
                            }
                            if (isMixerOn != mixerMotor.BitNumbers.All(bit => (_mainWindow.holdingRegister.motor & (1 << bit)) != 0))
                            {
                                isMixerOn = mixerMotor.BitNumbers.All(bit => (_mainWindow.holdingRegister.motor & (1 << bit)) != 0);
                            }
                            if (isFountOn && isMixerOn)  // both motores are on
                            {
                                if (_mainWindow.startRecipe == 1 && (_mainWindow.Heating == 10 || _mainWindow.cooling == 10 || _mainWindow.pouring == 10))
                                {
                                    _mainWindow.unPause = true;
                                }
                            }


                        }
                    });
                }


                await Task.Delay(10);
            }
            catch (Exception)
            {

            }
        }

    }

}
