using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Controls.Shapes;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.LogicalTree;
using Avalonia.Markup.Xaml;
using Avalonia.Media;
using Avalonia.Threading;
using AvaloniaApplication1.DataBase;
using DaireApplication.DataBase;
using DaireApplication.ViewModels;
using DaireApplication.Views;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Tracing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace DaireApplication;

public partial class Diagnostics : UserControl
{
    private MainWindow? _mainWindow;
    private ErrorSettingsTable _error=new();
    public ConfigrationTable _configration;
    private Process? _keyboardProcess;


    public string GrayColor="#666666";
    public string RedColor= "#FF0000";
    public string GreenColor= "#71C837";
    public string PinkColor= "#AF196F";
    public string OrangeColor= "#FF6600";
    public List<Rectangle> flagRectangles { get; set; }
    public List<Control> InputesElements { get; set; }
    public List<Control> MotoreState { get; set; }
    public List<Control> hvoOutPuts { get; set; }
    public List<Control> lvoOutPuts { get; set; }
    TextBlock targetText = new TextBlock();
    Button targetButton = new Button();
    float oldValue = 0;
    bool isNegative = false;
    bool _isAdvSettings;
    bool _isFromManualControl;
    public MachineTable _machine { get; set; }


    public Diagnostics()
    {

        InitializeComponent();

    }
    public Diagnostics(MainWindow mainWindow,bool isAdvSettings=false, bool isFromManualControl=false)
    {
        _mainWindow = mainWindow;
        _machine = new MachineTable();
        _configration = new();
        _isAdvSettings = isAdvSettings;
        _isFromManualControl = isFromManualControl;

        InitializeComponent();
        setDefaultSettings();
        getUiElementes();
        fcThreshold.AddHandler(TextInputEvent, OnTextInput, RoutingStrategies.Tunnel);
        heatConRange.AddHandler(TextInputEvent, OnTextInput, RoutingStrategies.Tunnel);
        fcThresholdBorder.AddHandler(InputElement.PointerPressedEvent, OnTextBoxFocused, RoutingStrategies.Tunnel, handledEventsToo: true);
        heatConRangeBorder.AddHandler(InputElement.PointerPressedEvent, OnTextBoxFocused, RoutingStrategies.Tunnel, handledEventsToo: true);

        AttachHandlers(_mainWindow.logoBtn, AdvanceSettingsView);
    }
    public void AttachHandlers(Button button, System.EventHandler<Avalonia.Input.HoldingRoutedEventArgs> func)
    {
        if (button != null)
        {
            button.Holding += func;

            button.PointerPressed += (sender, e) =>
            {
                // Simulate a long press on any pointer (mouse or touch)
                var point = e.GetPosition(button);
                func(sender, new HoldingRoutedEventArgs(HoldingState.Started, point, e.Pointer.Type));
            };

            button.PointerReleased += (sender, e) =>
            {
                // End simulated long press
                var point = e.GetPosition(button);
                func(sender, new HoldingRoutedEventArgs(HoldingState.Completed, point, e.Pointer.Type));
            };
        }
    }
    public void AdvanceSettingsView(object? sender, RoutedEventArgs e)
    {
        if (_mainWindow.ContentArea.Content == this)
        {
            _mainWindow.ContentArea.Content = new AdvanceSettings(_mainWindow,true,false);
        }

    }
    public void ResendConfig(object? sender, RoutedEventArgs e)
    {
        if (!_mainWindow.sendConfig)
        {
            _mainWindow.reSendHolding = true;
        }
    }
    public static void CloseApplication(object? sender, RoutedEventArgs e)
    {
        var lifetime = Application.Current?.ApplicationLifetime as IClassicDesktopStyleApplicationLifetime;
        lifetime?.Shutdown(); // This should correctly shut down the application
    }
    private async void motorClick(object? sender, RoutedEventArgs e)
    {
        if (sender is Button button)
        {
            var grid= button.Content as Grid;
            var stackPanel = grid.Children[0] as StackPanel;
            var text = stackPanel.Children[1] as TextBlock;
            if (text.Text=="ON")
            {
                _mainWindow.holdingRegister.motor = (ushort)(_mainWindow.holdingRegister.motor & ~(1 << int.Parse(grid.Tag.ToString())));

            }
            else if (text.Text == "OFF")
            {
                _mainWindow.holdingRegister.motor = (ushort)(_mainWindow.holdingRegister.motor | (1 << int.Parse(grid.Tag.ToString())));
            }
            await _mainWindow.WriteToSerialAsync("motorClick");

        }

    } 
    private async void hvoClick(object? sender, RoutedEventArgs e)
    {
        if (sender is Button button)
        {
            var grid= button.Content as Grid;
            var text = grid.Children[1] as TextBlock;
            if (text.Text=="ON")
            {
                _mainWindow.holdingRegister.hvOut = (ushort)(_mainWindow.holdingRegister.hvOut & ~(1 << int.Parse(grid.Tag.ToString())));

            }
            else if (text.Text == "OFF")
            {
                _mainWindow.holdingRegister.hvOut = (ushort)(_mainWindow.holdingRegister.hvOut | (1 << int.Parse(grid.Tag.ToString())));

            }
            await _mainWindow.WriteToSerialAsync("hvoClick");

        }

    } 
    private async void lvoClick(object? sender, RoutedEventArgs e)
    {
        if (sender is Button button)
        {
            var grid= button.Content as Grid;
            var stack= button.Content as StackPanel;
            if (grid!=null)
            {
                var text = grid.Children[1] as TextBlock;
                if (text.Text == "ON")
                {
                    _mainWindow.holdingRegister.lvOut = (ushort)(_mainWindow.holdingRegister.lvOut & ~(1 << int.Parse(grid.Tag.ToString())));

                }
                else if (text.Text == "OFF")
                {
                    _mainWindow.holdingRegister.lvOut = (ushort)(_mainWindow.holdingRegister.lvOut | (1 << int.Parse(grid.Tag.ToString())));
                }

            }
            else if(stack != null)
            {
                var text = stack.Children[1] as TextBlock;
                if (text.Text == "ON")
                {
                    _mainWindow.holdingRegister.lvOut = (ushort)(_mainWindow.holdingRegister.lvOut & ~(1 << int.Parse(stack.Tag.ToString())));

                }
                else if (text.Text == "OFF")
                {
                    _mainWindow.holdingRegister.lvOut = (ushort)(_mainWindow.holdingRegister.lvOut | (1 << int.Parse(stack.Tag.ToString())));
                }
            }
            await _mainWindow.WriteToSerialAsync("lvoClick");


        }

    }

    private async void resetErrorClick(object? sender, RoutedEventArgs e)
    {
        if (sender is Button button)
        {
            _mainWindow.holdingRegister.resetError = (ushort)(_mainWindow.holdingRegister.resetError | (1 << 0));
            await _mainWindow.WriteToSerialAsync("resetErrorClick");
        }
    }

    private async void ChangeTempMode(object sender, RoutedEventArgs e)
    {
        float number =0;

        if (sender is Border border) 
        {
            if (border.Tag.ToString()=="t1")
            {
                number = float.Parse(t1Text.Text);
            }
            else if(border.Tag.ToString() == "t2")
            {
                number = float.Parse(t2Text.Text);
            }
            else if (border.Tag.ToString() == "t3")
            {
                number = float.Parse(t3Text.Text);
            }
            else if (border.Tag.ToString() == "t4")
            {
                number = float.Parse(t4Text.Text);
            }
            var parent = border.Parent as StackPanel;
            var brother = parent.Children[1] as Border;

            List<TextBlock> allTexts= new ();
            if (brother.Tag?.ToString() == "t1")
            {
                allTexts.Add(t1Container.Children[0] as TextBlock);
                allTexts.Add(t1Container.Children[1] as TextBlock);
                allTexts.Add(t1Container.Children[2] as TextBlock);

            }
            else if (brother.Tag?.ToString() == "t2")
            {
                allTexts.Add(t2Container.Children[0] as TextBlock);
                allTexts.Add(t2Container.Children[1] as TextBlock);
                allTexts.Add(t2Container.Children[2] as TextBlock);
            }
            else if (brother.Tag?.ToString() == "t3")
            {
                allTexts.Add(t3Container.Children[0] as TextBlock);
                allTexts.Add(t3Container.Children[1] as TextBlock);
                allTexts.Add(t3Container.Children[2] as TextBlock);
            }
            else if (brother.Tag?.ToString() == "t4")
            {
                allTexts.Add(t4Container.Children[0] as TextBlock);
                allTexts.Add(t4Container.Children[1] as TextBlock);
                allTexts.Add(t4Container.Children[2] as TextBlock);
            }
          
            var button=border.Child as Button;
            if (button.Content.ToString()=="M") 
            {
                allTexts[0].Foreground = Brush.Parse("#231f20");  // black
                allTexts[1].Foreground = Brush.Parse("#af196f");  // pink
                allTexts[2].Foreground = Brush.Parse("#231f20");  // black
                button.Foreground = Brush.Parse("#af196f");
                button.Content = "A";
                if (button.Tag.ToString() == "t1")
                {
                    _mainWindow.holdingRegister.setTemp1 = (int)(number * 10);

                }
                else if (button.Tag.ToString() == "t2")
                {
                    _mainWindow.holdingRegister.setTemp2 = (int)(number * 10);


                }
                else if (button.Tag.ToString() == "t3")
                {
                    _mainWindow.holdingRegister.setTemp3 = (int)(number * 10);


                }
                else if (button.Tag.ToString() == "t4")
                {
                    _mainWindow.holdingRegister.setTemp4 = (int)(number * 10);


                }
                await _mainWindow.WriteToSerialAsync("DiagnosticsTemp");

            }
            else
            {
                foreach (var item in allTexts)
                {
                    item.Foreground = Brush.Parse("#808080");  //gray
                }
                
                button.Foreground = Brush.Parse("#4d4d4d");
                button.Content = "M";
                if (button.Tag.ToString()=="t1")
                {
                    _mainWindow.holdingRegister.setTemp1 = -10000;

                }
                else if (button.Tag.ToString() == "t2")
                {
                    _mainWindow.holdingRegister.setTemp2 = -10000;

                }
                else if (button.Tag.ToString() == "t3")
                {
                    _mainWindow.holdingRegister.setTemp3 = -10000;

                }
                else if (button.Tag.ToString() == "t4")
                {
                    _mainWindow.holdingRegister.setTemp4 = -10000;

                }
                await _mainWindow.WriteToSerialAsync("DiagnosticsTemp");


            }
        }
        else if(sender is Button btn)
        {
            if (btn.Tag.ToString() == "t1")
            {
                number = float.Parse(t1Text.Text);
            }
            else if (btn.Tag.ToString() == "t2")
            {
                number = float.Parse(t2Text.Text);
            }
            else if (btn.Tag.ToString() == "t3")
            {
                number = float.Parse(t3Text.Text);
            }
            else if (btn.Tag.ToString() == "t4")
            {
                number = float.Parse(t4Text.Text);
            }
            var border1 = btn.Parent as Border;
            var parent = border1.Parent as StackPanel;

            var brother = parent.Children[1] as Border;

            List<TextBlock> allTexts = new();
            if (brother.Tag?.ToString() == "t1")
            {
                allTexts.Add(t1Container.Children[0] as TextBlock);
                allTexts.Add(t1Container.Children[1] as TextBlock);
                allTexts.Add(t1Container.Children[2] as TextBlock);

            }
            else if (brother.Tag?.ToString() == "t2")
            {
                allTexts.Add(t2Container.Children[0] as TextBlock);
                allTexts.Add(t2Container.Children[1] as TextBlock);
                allTexts.Add(t2Container.Children[2] as TextBlock);
            }
            else if (brother.Tag?.ToString() == "t3")
            {
                allTexts.Add(t3Container.Children[0] as TextBlock);
                allTexts.Add(t3Container.Children[1] as TextBlock);
                allTexts.Add(t3Container.Children[2] as TextBlock);
            }
            else if (brother.Tag?.ToString() == "t4")
            {
                allTexts.Add(t4Container.Children[0] as TextBlock);
                allTexts.Add(t4Container.Children[1] as TextBlock);
                allTexts.Add(t4Container.Children[2] as TextBlock);
            }

            var button = border1.Child as Button;
            if (button.Content.ToString() == "M")
            {
                allTexts[0].Foreground = Brush.Parse("#231f20");  // black
                allTexts[1].Foreground = Brush.Parse("#af196f");  // pink
                allTexts[2].Foreground = Brush.Parse("#231f20");  // black
                button.Foreground = Brush.Parse("#af196f");
                button.Content = "A";
                if (button.Tag.ToString() == "t1")
                {
                    _mainWindow.holdingRegister.setTemp1 = (int)(number * 10);

                }
                else if (button.Tag.ToString() == "t2")
                {
                    _mainWindow.holdingRegister.setTemp2 = (int)(number * 10);


                }
                else if (button.Tag.ToString() == "t3")
                {
                    _mainWindow.holdingRegister.setTemp3 = (int)(number * 10);
                }
                else if (button.Tag.ToString() == "t4")
                {
                    _mainWindow.holdingRegister.setTemp4 = (int)(number * 10);
                }
                await _mainWindow.WriteToSerialAsync("DiagnosticsTemp");


            }
            else
            {
                foreach (var item in allTexts)
                {
                    item.Foreground = Brush.Parse("#808080");  //gray
                }

                button.Foreground = Brush.Parse("#4d4d4d");
                button.Content = "M";
                if (button.Tag.ToString() == "t1")
                {
                    _mainWindow.holdingRegister.setTemp1 = -10000;

                }
                else if (button.Tag.ToString() == "t2")
                {
                    _mainWindow.holdingRegister.setTemp2 = -10000;

                }
                else if (button.Tag.ToString() == "t3")
                {
                    _mainWindow.holdingRegister.setTemp3 = -10000;

                }
                else if (button.Tag.ToString() == "t4")
                {
                    _mainWindow.holdingRegister.setTemp4 = -10000;

                }
                await _mainWindow.WriteToSerialAsync("DiagnosticsTemp");

            }
        }
    }

    private void OnPopupOverlayPointerPressed(object sender, PointerPressedEventArgs e)
    {
        if (isNegative)
        {
            targetText.Text = "-" + oldValue.ToString("0.0");
        }
        else
        {
            targetText.Text = "+" + oldValue.ToString("0.0");
        }
        keyBoardPopup.IsVisible = false;
    }
    private void InnerPopupPointerPressed(object? sender, PointerPressedEventArgs e)
    {
        e.Handled = true;
    }
    private void OnKeyClick(object? sender, RoutedEventArgs e)
    {
        if (sender is Button button)
        {
            if ((button.Content=="+"|| button.Content == "-")&& targetText.Text.Length>0)
            {

            }
            else if((targetText.Text.Length==0 && button.Content == ".")||(targetText.Text.Contains(".")&& button.Content == "."))
            {

            }
            else
            {
                targetText.Text += button.Content;
            }
           
        }

    }
    private void OnBackClick(object? sender, RoutedEventArgs e)
    {
        if (!string.IsNullOrEmpty(targetText.Text))
        {
            // Remove the last character from the text box
            targetText.Text = targetText.Text.Remove(targetText.Text.Length - 1, 1);
            //number = number.Remove(number.Length - 1);
        }

    }
    private async void EnterClick(object? sender, RoutedEventArgs e)
    {
        if (sender is Button button)
        {
            bool canEdit = targetButton.Content == "A";
            if (!string.IsNullOrEmpty(targetText.Text))
            {
                float number = float.Parse(targetText.Text);

                if (char.IsDigit(targetText.Text[0]))
                {
                    targetText.Text = "+" + number.ToString("0.0");
                }
                else
                {
                    targetText.Text = number.ToString("0.0");
                }

                var machine = _machine.ReadMachine();
                if (button.Tag.ToString() == "t1")
                {
                    if (canEdit)
                    {
                        _mainWindow.holdingRegister.setTemp1 = (int)(number * 10);

                    }
                    machine.setTemp1 = number;

                }
                else if (button.Tag.ToString() == "t2")
                {
                    if (canEdit)
                    {
                        _mainWindow.holdingRegister.setTemp2 = (int)(number * 10);

                    }
                    machine.setTemp2 = number;


                }
                else if (button.Tag.ToString() == "t3")
                {
                    if (canEdit)
                    {
                        _mainWindow.holdingRegister.setTemp3 = (int)(number * 10);
                    }
                    machine.setTemp3 = number;
                }
                else if (button.Tag.ToString() == "t4")
                {
                    if (canEdit)
                    {
                        _mainWindow.holdingRegister.setTemp4 = (int)(number * 10);
                    }
                    machine.setTemp4 = number;
                }
                _machine.UpdateMachine(machine);
                getUiElementes();
                if (canEdit)
                {
                    await _mainWindow.WriteToSerialAsync("DiagnosticsEnter");

                }

                keyBoardPopup.IsVisible = false;
            }
         
        }
        
    }
    private void ShowNumberKeyBoard(object? sender, PointerPressedEventArgs e)
    {
        if (sender is Border border)
        {
            var parent = border.Parent as StackPanel;
            var brother = parent.Children[0] as Border;
            targetButton = brother.Child as Button;
            if (border.Tag?.ToString() == "t1")
            {
                targetText = t1Text;
            }
            else if (border.Tag?.ToString() == "t2")
            {
                targetText = t2Text;
            }
            else if (border.Tag?.ToString() == "t3")
            {
                targetText = t3Text;
            }
            else if (border.Tag?.ToString() == "t4")
            {
                targetText = t4Text;
            }
            enterBtn.Tag = border.Tag;

            isNegative = targetText.Text.StartsWith("-");

            oldValue = float.Parse(targetText.Text.Substring(1));
            targetText.Text = "";
            keyBoardPopup.IsVisible = true;

        }

    }

    private async void OnIgnorePidPopupOverlayPointerPressed(object? sender, RoutedEventArgs e)
    {
        pidPopupOverlay.IsVisible = false;
    }
    private async void showInnerPid(object? sender, RoutedEventArgs e)
    {
        if (sender is Button button)
        {
            var configratipn = _configration.ReadConfigrationById(button.Tag.ToString());
            pidPopupOverlay.IsVisible = false;
            header.Text = button.Content.ToString();
            header.Tag = button.Tag;
            
            // Set slider values instead of text box values
            kpSlider.Value = configratipn.kp;
            kiSlider.Value = configratipn.ki;
            kdSlider.Value = configratipn.kd;
            klSlider.Value = configratipn.kl;
            
            // Update the display values
            kpSliderValue.Text = configratipn.kp.ToString();
            kiSliderValue.Text = configratipn.ki.ToString();
            kdSliderValue.Text = configratipn.kd.ToString();
            klSliderValue.Text = configratipn.kl.ToString();
            
            fcThreshold.Text = configratipn.FC_Threshold.ToString("0.0");
            heatConRange.Text = configratipn.HeatConRange.ToString("0.0");
            innerPidPopupOverlay.IsVisible = true;
        }
    }
    private async void OnIgnoreInnerPidPopupOverlayPointerPressed(object? sender, RoutedEventArgs e)
    {
        innerPidPopupOverlay.IsVisible = false;
        pidPopupOverlay.IsVisible = true;
    }
    private void OnKeyUp(object? sender, KeyEventArgs e)
    {
        if (sender is TextBox textBox)
        {
            if (textBox != null && float.TryParse(textBox.Text, out float value))
            {
                if (textBox.Name == "heatConRange")
                {
                    if (value > 25.0)
                    {
                        textBox.Text = "25.0";
                    }

                }
                else
                {
                    if (value > 100)
                    {
                        textBox.Text = "100";
                    }
                }
                // Check if the value exceeds 100 and reset to 100 if necessary.

            }
        }

    }
    private async void YesBtnClick(object? sender, RoutedEventArgs e)
    {
        if (sender is Button button)
        {
            var configration = _configration.ReadConfigrationById(header.Tag.ToString());
            if (configration!=null)
            {
                // Read values from sliders instead of text boxes
                configration.kp = (int)kpSlider.Value;
                configration.ki = (int)kiSlider.Value;
                configration.kd = (int)kdSlider.Value;
                configration.kl = (int)klSlider.Value;
                
                if (string.IsNullOrEmpty(fcThreshold.Text))
                {
                    configration.FC_Threshold = 0;
                }
                else
                {
                    configration.FC_Threshold = float.Parse(fcThreshold.Text);
                }
                if (string.IsNullOrEmpty(heatConRange.Text))
                {
                    configration.HeatConRange = 1.0F;
                }
                else
                {
                    if (float.TryParse(heatConRange.Text, out float value))
                    {
                        if (value<1.0)
                        {
                            configration.HeatConRange = 1.0F;
                        }
                        else
                        {
                            configration.HeatConRange = float.Parse(heatConRange.Text);
                        }
                    }
                    else
                    {
                        configration.HeatConRange = 1.0F;
                    }
                }

                _configration.UpdateConfigration(configration);
                _mainWindow.reSendHolding = true;
                CloseKeyboard();

                innerPidPopupOverlay.IsVisible = false;
                pidPopupOverlay.IsVisible = true;
            }
        }
    }
    private void CloseKeyboard()
    {
        try
        {
            if (_keyboardProcess != null)
            {
                // Kill the keyboard process
                _keyboardProcess.Kill();
                _keyboardProcess.Dispose();
                _keyboardProcess = null;

                // Force kill any remaining keyboard processes
                var processKill = new Process
                {
                    StartInfo = new ProcessStartInfo
                    {
                        FileName = "killall",
                        Arguments = "-9 onboard matchbox-keyboard florence",  // Common Linux on-screen keyboards
                        UseShellExecute = false,
                        CreateNoWindow = true
                    }
                };
                processKill.Start();
                processKill.WaitForExit(1000);
                processKill.Dispose();
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error closing keyboard: {ex.Message}");
        }
    }
    private (string? fileName, string args) GetKeyboardCommand()
    {
        if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            return ("osk.exe", "");
        if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            return ("onboard", ""); // or "florence", "matchbox-keyboard"
        return (null, "");
    }
    private async void OnTextBoxFocused(object? sender, PointerPressedEventArgs e)
    {
        if (_keyboardProcess is { HasExited: false })
            return;

        var (fileName, args) = GetKeyboardCommand();
        if (fileName is null)
            return;

        _keyboardProcess = new Process
        {
            StartInfo = new ProcessStartInfo
            {
                FileName = fileName,
                Arguments = args,
                UseShellExecute = true,
                WorkingDirectory = "/usr/bin"
            },
            EnableRaisingEvents = true
        };


        try
        {
            _keyboardProcess.Start();



            Dispatcher.UIThread.Post(() =>
            {
                if (sender is Border border)
                {
                    var textbox = border.Child as TextBox;
                    textbox.SelectionStart = 0;
                    textbox.SelectionEnd = textbox.Text?.Length ?? 0;
                }
            });

        }
        catch
        {
            // fail silently if keyboard not found
        }
    }
    private void OnTextInput(object? sender, TextInputEventArgs e)
    {
        if (sender is TextBox textBox)
        {
            string newText = textBox.Text + e.Text;
            if (!Regex.IsMatch(newText, @"^\d*\.?\d*$"))
            {
                e.Handled = true;
            }
        }
    }
    private void OnTextInputOnlyInteager(object? sender, TextInputEventArgs e)
    {
        if (sender is TextBox textBox)
        {
            string newText = textBox.Text + e.Text;
            if (!Regex.IsMatch(newText, @"^\d*$"))
            {
                e.Handled = true;
            }
        }
    }
    private async void showPidPopUp(object? sender, RoutedEventArgs e)
    {
        pidPopupOverlay.IsVisible = true;

    }


    private void getUiElementes() 
    {
        var error = _error.ReadErrorSettings()[0];

        if (error.phaseNumber == 1)
        {
            phaseContainer.Background = Avalonia.Media.Brushes.Gray;
            phaseContainer.IsEnabled = false;
        }
        else
        {
            phaseContainer.Background = Brush.Parse("#E6E6E6");
            phaseContainer.IsEnabled = true;
        }

        flagRectangles = this.GetLogicalDescendants()
               .OfType<Rectangle>()
               .Where(cb => cb.Classes.Contains("flag"))
               .ToList();

         InputesElements = this.GetLogicalDescendants()
                 .OfType<Control>()
                 .Where(c => c.Classes.Contains("in") && (c is Grid || c is Ellipse))
                 .ToList();
        MotoreState = this.GetLogicalDescendants()
                 .OfType<Control>()
                 .Where(c => c.Classes.Contains("motorState") && (c is Grid || c is Ellipse))
                 .ToList();
        hvoOutPuts = this.GetLogicalDescendants()
                 .OfType<Control>()
                 .Where(c => c.Classes.Contains("hvo") && (c is Grid || c is Ellipse))
                 .ToList();
        lvoOutPuts = this.GetLogicalDescendants()
                .OfType<Control>()
                .Where(c => c.Classes.Contains("lvo") && (c is Grid||c is StackPanel || c is Ellipse))
                .ToList();
        var machine=_machine.ReadMachine();
        t1Text.Text = char.IsDigit(machine.setTemp1.ToString()[0])?"+"+ machine.setTemp1.ToString(): machine.setTemp1.ToString();
        t2Text.Text = char.IsDigit(machine.setTemp2.ToString()[0]) ? "+" + machine.setTemp2.ToString() : machine.setTemp2.ToString();
        t3Text.Text = char.IsDigit(machine.setTemp3.ToString()[0]) ? "+" + machine.setTemp3.ToString() : machine.setTemp3.ToString();
        t4Text.Text = char.IsDigit(machine.setTemp4.ToString()[0]) ? "+" + machine.setTemp4.ToString() : machine.setTemp4.ToString();


    }
    private void setDefaultSettings()
    {
        var stackPanel = _mainWindow.HomeTrack.Parent as StackPanel;
        _mainWindow.minimizeBtn.IsVisible = false;

        if (_isFromManualControl)
        {
            // Special UI setup when called from ManualControl
            _mainWindow.HomeTrack.IsVisible = true;
            _mainWindow.HomePolygon.Stroke = Avalonia.Media.Brushes.Black;
            _mainWindow.RecipeSelTrack.IsVisible = false;
            _mainWindow.RunInterfaceTrack.IsVisible = false;
            _mainWindow.RecipePanelTrack.IsVisible = true;
            _mainWindow.RecipePanelPolygon.Stroke = Avalonia.Media.Brushes.Black;
            _mainWindow.RecipeEditTrack.IsVisible = false;
            _mainWindow.SettingTrack.IsVisible = false;
            _mainWindow.AdvanceSettingsTrack.IsVisible = false;
            _mainWindow.ManualControlTrack.IsVisible = true;
            _mainWindow.ManualControlPolygon.Stroke = Avalonia.Media.Brushes.Black;
        }
        else
        {
            // Original logic for other callers
            //Set Track Up
            _mainWindow.HomeTrack.IsVisible = true;
            //_mainWindow.HomePolygon.Stroke = Avalonia.Media.Brushes.Black;
            _mainWindow.RecipeSelTrack.IsVisible = false;
            _mainWindow.RunInterfaceTrack.IsVisible = false;
            _mainWindow.RecipePanelTrack.IsVisible = false;
            _mainWindow.RecipeEditTrack.IsVisible = false;
            if (_isAdvSettings)
            {
                _mainWindow.SettingTrack.IsVisible = false;
                _mainWindow.AdvanceSettingsTrack.IsVisible = true;
                _mainWindow.AdvanceSettingsPolygon.Stroke = Avalonia.Media.Brushes.Black;

            }
            else
            {
                _mainWindow.SettingTrack.IsVisible = true;
                _mainWindow.SettingPolygon.Stroke = Avalonia.Media.Brushes.Black;
                _mainWindow.AdvanceSettingsTrack.IsVisible = false;

            }
        }

        _mainWindow.DiagnosticsTrack.IsVisible = true;
        _mainWindow.DiagnosticsPolygon.Stroke = Brush.Parse("#A4275D");
        // Remove the button from its current position
        stackPanel.Children.Remove(_mainWindow.DiagnosticsTrack);

        // Add it back at the end of the StackPanel
        stackPanel.Children.Add(_mainWindow.DiagnosticsTrack);

        _mainWindow.TitleBtn.IsVisible = false;

        _mainWindow.TitleBtn.IsVisible = true;
        _mainWindow.Title.Text = "DMC7A";
        //Set Footer
        _mainWindow.footerMsg.IsVisible = true;
        _mainWindow.footerMsg.Text= "Read Values, And Control Outputs Manually";
        _mainWindow.footerMsg.Foreground= Brush.Parse("#A4275D");
        _mainWindow.footer.Background = Avalonia.Media.Brushes.WhiteSmoke;
        _mainWindow.footerDate.Text = DateTime.Now.ToString("dd/MM/yyyy");
        _mainWindow.footerTime.Text = DateTime.Now.ToString("hh:mm tt");
        _mainWindow.footerDateContainer.IsVisible = true;
        _mainWindow.footerStartBtn.IsVisible = false;
        _mainWindow.adminBtns.IsVisible = false;
    }

    // KP Slider and Button Event Handlers
    private void KpSliderValueChanged(object? sender, RoutedEventArgs e)
    {
        if (kpSliderValue != null && sender is Slider slider)
        {
            kpSliderValue.Text = ((int)slider.Value).ToString();
        }
    }

    private void KpMinusClick(object? sender, RoutedEventArgs e)
    {
        if (kpSlider.Value > kpSlider.Minimum)
        {
            kpSlider.Value--;
        }
    }

    private void KpPlusClick(object? sender, RoutedEventArgs e)
    {
        if (kpSlider.Value < kpSlider.Maximum)
        {
            kpSlider.Value++;
        }
    }

    // KI Slider and Button Event Handlers
    private void KiSliderValueChanged(object? sender, RoutedEventArgs e)
    {
        if (kiSliderValue != null && sender is Slider slider)
        {
            kiSliderValue.Text = ((int)slider.Value).ToString();
        }
    }

    private void KiMinusClick(object? sender, RoutedEventArgs e)
    {
        if (kiSlider.Value > kiSlider.Minimum)
        {
            kiSlider.Value--;
        }
    }

    private void KiPlusClick(object? sender, RoutedEventArgs e)
    {
        if (kiSlider.Value < kiSlider.Maximum)
        {
            kiSlider.Value++;
        }
    }

    // KD Slider and Button Event Handlers
    private void KdSliderValueChanged(object? sender, RoutedEventArgs e)
    {
        if (kdSliderValue != null && sender is Slider slider)
        {
            kdSliderValue.Text = ((int)slider.Value).ToString();
        }
    }

    private void KdMinusClick(object? sender, RoutedEventArgs e)
    {
        if (kdSlider.Value > kdSlider.Minimum)
        {
            kdSlider.Value--;
        }
    }

    private void KdPlusClick(object? sender, RoutedEventArgs e)
    {
        if (kdSlider.Value < kdSlider.Maximum)
        {
            kdSlider.Value++;
        }
    }

    // KL Slider and Button Event Handlers
    private void KlSliderValueChanged(object? sender, RoutedEventArgs e)
    {
        if (klSliderValue != null && sender is Slider slider)
        {
            klSliderValue.Text = ((int)slider.Value).ToString();
        }
    }

    private void KlMinusClick(object? sender, RoutedEventArgs e)
    {
        if (klSlider.Value > klSlider.Minimum)
        {
            klSlider.Value--;
        }
    }

    private void KlPlusClick(object? sender, RoutedEventArgs e)
    {
        if (klSlider.Value < klSlider.Maximum)
        {
            klSlider.Value++;
        }
    }
}