using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes;
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 DynamicData;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using static DaireApplication.Views.MainWindow;

namespace DaireApplication;

public partial class AdvanceSettings : UserControl
{
    public Mapping _mapping;
    public ConfigrationTable _configration;
    public List<Mapping> _mappingRecordes;
    MainWindow _mainWindow;
    private Process? _keyboardProcess;
    public ErrorSettingsTable _error = new();
    TextBlock targetText = new TextBlock();
    float oldValue = 0;
    bool _isDiag;
    bool _isSoftware;
    public AdvanceSettings(MainWindow mainWindow,bool isDiag=false,bool isSoftware=false)
    {
        InitializeComponent();
        _mainWindow = mainWindow;
        _mapping = new Mapping();
        _mappingRecordes = _mapping.ReadMappings();
        _configration = new();
        _isDiag = isDiag;
        _isSoftware = isSoftware;

        setDefaultValues();
        // Remove the old text box event handlers since we're using sliders now
        // kp.AddHandler(TextInputEvent, OnTextInputOnlyInteager, RoutingStrategies.Tunnel);
        // ki.AddHandler(TextInputEvent, OnTextInputOnlyInteager, RoutingStrategies.Tunnel);
        // kd.AddHandler(TextInputEvent, OnTextInputOnlyInteager, RoutingStrategies.Tunnel);
        // kl.AddHandler(TextInputEvent, OnTextInputOnlyInteager, RoutingStrategies.Tunnel);
        fcThreshold.AddHandler(TextInputEvent, OnTextInput, RoutingStrategies.Tunnel);
        heatConRange.AddHandler(TextInputEvent, OnTextInput, RoutingStrategies.Tunnel);
        // Remove the old border event handlers since we're using sliders now
        // kpBorder.AddHandler(InputElement.PointerPressedEvent, OnTextBoxFocused, RoutingStrategies.Tunnel, handledEventsToo: true);
        // kiBorder.AddHandler(InputElement.PointerPressedEvent, OnTextBoxFocused, RoutingStrategies.Tunnel, handledEventsToo: true);
        // kdBorder.AddHandler(InputElement.PointerPressedEvent, OnTextBoxFocused, RoutingStrategies.Tunnel, handledEventsToo: true);
        // klBorder.AddHandler(InputElement.PointerPressedEvent, OnTextBoxFocused, RoutingStrategies.Tunnel, handledEventsToo: true);
        fcThresholdBorder.AddHandler(InputElement.PointerPressedEvent, OnTextBoxFocused, RoutingStrategies.Tunnel, handledEventsToo: true);
        heatConRangeBorder.AddHandler(InputElement.PointerPressedEvent, OnTextBoxFocused, RoutingStrategies.Tunnel, handledEventsToo: true);
        AttachHandlers(_mainWindow.UserName, CloseApplication);

        setDefaultSettings();

    }
    public AdvanceSettings()
    {
        InitializeComponent();
    }
    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 static void CloseApplication(object? sender, RoutedEventArgs e)
    {
        var lifetime = Application.Current?.ApplicationLifetime as IClassicDesktopStyleApplicationLifetime;
        lifetime?.Shutdown(); // This should correctly shut down the application
    }
    private void HVOChanged(object? sender, RoutedEventArgs e)
    {
        if (sender is ComboBox comboBox)
        {
            if (comboBox.SelectedItem is ComboBoxItem selectedItem)
            {
                // Get the displayed content

                //HVO
               var result= _mappingRecordes.FindAll(x => x.Address == "1" && x.IsRead==false).Find(c=>c.Name==selectedItem.Content.ToString());
                if (result!=null)
                {
                    if (!result.BitNumbers.Contains(int.Parse(comboBox.Tag.ToString())))
                    {
                        var oldRecord = _mappingRecordes.Find(x => x.Address == "1" && x.IsRead == false && x.BitNumbers.Contains(int.Parse(comboBox.Tag.ToString())));
                        if (oldRecord!=null)
                        {
                            _mapping.DeleteBitNumber(oldRecord.Id, int.Parse(comboBox.Tag.ToString()));

                        }
                        result.BitNumbers.Add(int.Parse(comboBox.Tag.ToString()));
                        _mapping.UpdateMapping(result);
                        setDefaultValues();
                    }

                }
                else
                {
                    var oldRecord = _mappingRecordes.Find(x => x.Address == "1" && x.IsRead == false && x.BitNumbers.Contains(int.Parse(comboBox.Tag.ToString())));
                    if (oldRecord != null)
                    {
                        _mapping.DeleteBitNumber(oldRecord.Id, int.Parse(comboBox.Tag.ToString()));

                    }
                }


                _mappingRecordes = _mapping.ReadMappings();
                _mainWindow._mapping = _mappingRecordes;
                var configrations = _configration.ReadConfigrations();
                var compressor = _mappingRecordes.Find(x => x.Name == "Compressor");
                var water = _mappingRecordes.Find(x => x.Name == "Water");
                if (compressor != null && water != null)
                {
                    if (compressor.BitNumbers.Count > 0 )
                    {
                        configrations[2].FC_out = compressor.BitNumbers.Concat(water.BitNumbers).ToList();
                        configrations[3].FC_out = compressor.BitNumbers.Concat(water.BitNumbers).ToList();

                    }
                    else
                    {
                        configrations[2].FC_out = [-1];
                        configrations[3].FC_out = [-1];

                    }
                    if (water.BitNumbers.Count > 0)
                    {
                        configrations[2].SC_out = water.BitNumbers;
                        configrations[3].SC_out = water.BitNumbers;
                    }
                    else
                    {
                        configrations[2].SC_out = [-1];
                        configrations[3].SC_out = [-1];
                    }
                    _configration.UpdateConfigration(configrations[2]);
                    _configration.UpdateConfigration(configrations[3]);

                }
                foreach (var item in configrations)
                {
                    var namedMap = _mappingRecordes.Find(x => x.Name == item.name);
                    if (namedMap!=null)
                    {
                        if (namedMap.BitNumbers.Count>0)
                        {
                            item.H_out = namedMap.BitNumbers;
                            if (namedMap.Name!= "HELIX Heater")
                            {
                                item.FC_out = [-1];
                                item.SC_out = [-1];
                            }
                            _configration.UpdateConfigration(item);
                        }
                        else
                        {
                            item.H_out =[-1];
                            if (namedMap.Name != "HELIX Heater")
                            {
                                item.FC_out = [-1];
                                item.SC_out = [-1];
                            }
                            _configration.UpdateConfigration(item);
                        }
                    }
                    else
                    {

                    }
                }
                configrations[3].H_out = configrations[2].H_out;
                _configration.UpdateConfigration(configrations[3]);


                _mainWindow.sendConfig = true;
            }

        }
    }

    private void TChanged(object? sender, RoutedEventArgs e)
    {
        if (sender is ComboBox comboBox)
        {
            if (comboBox.SelectedItem is ComboBoxItem selectedItem)
            {
                // Get the displayed content

                //HVO
                var result = _mappingRecordes.Find(c => c.Name.ToLower() == selectedItem.Tag.ToString().ToLower());
                if (result != null)
                {
                    if (!result.BitNumbers.Contains(int.Parse(comboBox.Tag.ToString())))
                    {
                        var oldRecord = _mappingRecordes.Find(x => x.Name.EndsWith("Temp") && x.BitNumbers.Contains(int.Parse(comboBox.Tag.ToString())));
                        if (oldRecord != null)
                        {
                            _mapping.DeleteBitNumber(oldRecord.Id, int.Parse(comboBox.Tag.ToString()));

                        }
                        result.BitNumbers.Add(int.Parse(comboBox.Tag.ToString()));
                        _mapping.UpdateMapping(result);
                        setDefaultValues();
                    }

                }
                else
                {
                    var oldRecord = _mappingRecordes.Find(x => x.Name.EndsWith("Temp") && x.BitNumbers.Contains(int.Parse(comboBox.Tag.ToString())));
                    if (oldRecord != null)
                    {
                        _mapping.DeleteBitNumber(oldRecord.Id, int.Parse(comboBox.Tag.ToString()));
                        setDefaultValues();


                    }
                }


                _mappingRecordes = _mapping.ReadMappings();
                _mainWindow._mapping = _mappingRecordes;

            }

        }
    }  
    private void LOVChanged(object? sender, RoutedEventArgs e)
    {
        if (sender is ComboBox comboBox)
        {
            if (comboBox.SelectedItem is ComboBoxItem selectedItem)
            {
                var result = _mappingRecordes.FindAll(x => x.Address == "2").Find(c => c.Name.ToLower() == selectedItem.Tag.ToString().ToLower());
                if (result != null)
                {
                    if (!result.BitNumbers.Contains(int.Parse(comboBox.Tag.ToString())))
                    {
                        var oldRecord = _mappingRecordes.Find(x => x.Address == "2" && x.BitNumbers.Contains(int.Parse(comboBox.Tag.ToString())));
                        if (oldRecord != null)
                        {
                            _mapping.DeleteBitNumber(oldRecord.Id, int.Parse(comboBox.Tag.ToString()));

                        }
                        result.BitNumbers.Add(int.Parse(comboBox.Tag.ToString()));
                        _mapping.UpdateMapping(result);
                        setDefaultValues();
                    }

                }
                else
                {
                    var oldRecord = _mappingRecordes.Find(x => x.Address == "2" && x.BitNumbers.Contains(int.Parse(comboBox.Tag.ToString())));
                    if (oldRecord != null)
                    {
                        _mapping.DeleteBitNumber(oldRecord.Id, int.Parse(comboBox.Tag.ToString()));
                        setDefaultValues();


                    }
                }
                _mappingRecordes = _mapping.ReadMappings();
                _mainWindow._mapping = _mappingRecordes;

            }

        }
    } 
    private void InChanged(object? sender, RoutedEventArgs e)
    {
        if (sender is ComboBox comboBox)
        {
            if (comboBox.SelectedItem is ComboBoxItem selectedItem)
            {
                // Get the displayed content

                //HVO
                var result = _mappingRecordes.FindAll(x => x.Address == "1" &&x.IsRead==true).Find(c => c.Name.ToLower() == selectedItem.Content.ToString().ToLower());
                if (result != null)
                {
                    if (!result.BitNumbers.Contains(int.Parse(comboBox.Tag.ToString())))
                    {
                        var oldRecord = _mappingRecordes.Find(x => x.Address == "1" && x.IsRead == true && x.BitNumbers.Contains(int.Parse(comboBox.Tag.ToString())));
                        if (oldRecord != null)
                        {
                            _mapping.DeleteBitNumber(oldRecord.Id, int.Parse(comboBox.Tag.ToString()));

                        }
                        result.BitNumbers.Add(int.Parse(comboBox.Tag.ToString()));
                        _mapping.UpdateMapping(result);
                        setDefaultValues();
                    }

                }
                else
                {
                    var oldRecord = _mappingRecordes.Find(x => x.Address == "1" && x.IsRead == true && x.BitNumbers.Contains(int.Parse(comboBox.Tag.ToString())));
                    if (oldRecord != null)
                    {
                        _mapping.DeleteBitNumber(oldRecord.Id, int.Parse(comboBox.Tag.ToString()));
                        setDefaultValues();


                    }
                }


                _mappingRecordes = _mapping.ReadMappings();
                _mainWindow._mapping = _mappingRecordes;

            }

        }
    }
    private void MotChanged(object? sender, RoutedEventArgs e)
    {
        if (sender is ComboBox comboBox)
        {
            if (comboBox.SelectedItem is ComboBoxItem selectedItem)
            {
                var result = _mappingRecordes.FindAll(x => x.Address == "3").Find(c => c.Name.ToLower() == selectedItem.Tag.ToString().ToLower());
                if (result != null)
                {
                    if (!result.BitNumbers.Contains(int.Parse(comboBox.Tag.ToString())))
                    {
                        var oldRecord = _mappingRecordes.Find(x => x.Address == "3" && x.BitNumbers.Contains(int.Parse(comboBox.Tag.ToString())));
                        if (oldRecord != null)
                        {
                            _mapping.DeleteBitNumber(oldRecord.Id, int.Parse(comboBox.Tag.ToString()));

                        }
                        result.BitNumbers.Add(int.Parse(comboBox.Tag.ToString()));
                        _mapping.UpdateMapping(result);
                        setDefaultValues();
                    }

                }
                else
                {
                    var oldRecord = _mappingRecordes.Find(x => x.Address == "3" && x.BitNumbers.Contains(int.Parse(comboBox.Tag.ToString())));
                    if (oldRecord != null)
                    {
                        _mapping.DeleteBitNumber(oldRecord.Id, int.Parse(comboBox.Tag.ToString()));
                        setDefaultValues();


                    }
                }


                _mappingRecordes = _mapping.ReadMappings();
                _mainWindow._mapping = _mappingRecordes;

            }

        }
    }



    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 async void OnIgnoreInnerPidPopupOverlayPointerPressed(object? sender, RoutedEventArgs e)
    {
        innerPidPopupOverlay.IsVisible = false;
        pidPopupOverlay.IsVisible = true;



    }
    private async void OnIgnorePidPopupOverlayPointerPressed(object? sender, RoutedEventArgs e)
    {
        pidPopupOverlay.IsVisible = false;
    }
    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.sendConfig = true;
                CloseKeyboard();

                innerPidPopupOverlay.IsVisible = false;
                pidPopupOverlay.IsVisible = true;

            }
        }



    }

    private async void showPidPopUp(object? sender, RoutedEventArgs e)
    {
        pidPopupOverlay.IsVisible = true;

    } 
    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;

        }

    }

    // 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++;
        }
    }

    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 gridButtonClick(object? sender, RoutedEventArgs e)
    {
        var error = _error.ReadErrorSettings()[0];
        if (gridValue.Text == "50Hz")
        {
            error.gridFreq = 60;
            _error.UpdateError(error);
            setDefaultValues();

        }
        else
        {
            error.gridFreq = 50;
            _error.UpdateError(error);
            setDefaultValues();
        }
       
    }
    private async void supplyButtonClick(object? sender, RoutedEventArgs e)
    {
        var error = _error.ReadErrorSettings()[0];
        int bit = 11;

        if (phasesNumberValue.Text == "3-Phases")
        {
            error.phaseNumber = 1;
            _error.UpdateError(error);
            setDefaultValues();
            _mainWindow.holdingRegister.resetError |= (ushort)(1 << bit);
        }
        else
        {
            error.phaseNumber = 3;
            _error.UpdateError(error);
            _mainWindow.holdingRegister.resetError &= (ushort)~(1 << bit);


            setDefaultValues();

        }
        await _mainWindow.WriteToSerialAsync("supplyButtonClick");
    }
    private async void voltageButtonClick(object? sender, RoutedEventArgs e)
    {
        var error = _error.ReadErrorSettings()[0];
        int bit = 12;

        if (voltageNumberValue.Text.Contains("220"))
        {
            error.phaseVoltage = 110;
            _error.UpdateError(error);
            setDefaultValues();
            _mainWindow.holdingRegister.resetError |= (ushort)(1 << bit);
        }
        else
        {
            error.phaseVoltage =220;
            _error.UpdateError(error);
            _mainWindow.holdingRegister.resetError &= (ushort)~(1 << bit);


            setDefaultValues();

        }
        await _mainWindow.WriteToSerialAsync("voltageButtonClick");
    }

    private async void extPowerClick(object? sender, RoutedEventArgs e)
    {
        var error = _error.ReadErrorSettings()[0];
        if (extPowerValue.Text == "Yes")
        {
            error.extPower = false;
            _error.UpdateError(error);
            setDefaultValues();


        }
        else
        {
            error.extPower = true;
            _error.UpdateError(error);
            setDefaultValues();

        }
    }
    private void setDefaultValues() 
    {
        _mappingRecordes = _mapping.ReadMappings();
        var allHVOComboBox= this.GetLogicalDescendants()
                   .OfType<ComboBox>()
                   .Where(cb => cb.Classes.Contains("HVO"))
                   .ToList();
        //HVO
        for (int i = 0; i < allHVOComboBox.Count; i++)
        {
            var result = _mappingRecordes.FindAll(x => x.Address == "1" && x.IsRead==false ).Find(c => c.BitNumbers.Contains(int.Parse(allHVOComboBox[i].Tag.ToString())));
            if (result != null)
            {
                allHVOComboBox[i].SelectedIndex = result.Id - 11;
            }
            else
            {
                allHVOComboBox[i].SelectedIndex = 6;

            }
        }
        // IN
        var allINComboBox = this.GetLogicalDescendants()
                 .OfType<ComboBox>()
                 .Where(cb => cb.Classes.Contains("in"))
                 .ToList();
        for (int i = 0; i < allINComboBox.Count; i++)
        {
            var result = _mappingRecordes.FindAll(x => x.Address == "1"&&x.IsRead==true).Find(c => c.BitNumbers.Contains(int.Parse(allINComboBox[i].Tag.ToString())));
            if (result != null)
            {
                allINComboBox[i].SelectedIndex = result.Id - 1;
            }
            else
            {
                allINComboBox[i].SelectedIndex = 3;

            }
        }

        //LOV
        var allLOVComboBox = this.GetLogicalDescendants()
                 .OfType<ComboBox>()
                 .Where(cb => cb.Classes.Contains("lov"))
                 .ToList();
        for (int i = 0; i < allLOVComboBox.Count; i++)
        {
            var result = _mappingRecordes.FindAll(x => x.Address == "2" && x.IsRead == false).Find(c => c.BitNumbers.Contains(int.Parse(allLOVComboBox[i].Tag.ToString())));
            if (result != null)
            {
                allLOVComboBox[i].SelectedIndex = result.Id - 8;
            }
            else
            {
                allLOVComboBox[i].SelectedIndex = 3;

            }
        }
        //  T

        var allTComboBox = this.GetLogicalDescendants()
                  .OfType<ComboBox>()
                  .Where(cb => cb.Classes.Contains("T"))
                  .ToList();
        for (int i = 0; i < allTComboBox.Count; i++)
        {
            var result = _mappingRecordes.FindAll(x => x.Name.EndsWith("Temp")).Find(c => c.BitNumbers.Contains(int.Parse(allTComboBox[i].Tag.ToString())));

            if (result != null)
            {
                allTComboBox[i].SelectedIndex = result.Id - 4;
            }
            else
            {
                allTComboBox[i].SelectedIndex = 5;

            }
        }
        // MOT
        var allMotComboBox = this.GetLogicalDescendants()
               .OfType<ComboBox>()
               .Where(cb => cb.Classes.Contains("mot"))
               .ToList();
        for (int i = 0; i < allMotComboBox.Count; i++)
        {
            var result = _mappingRecordes.FindAll(x => x.Address == "3" && x.IsRead==false).Find(c => c.BitNumbers.Contains(int.Parse(allMotComboBox[i].Tag.ToString())));
            if (result != null)
            {
                allMotComboBox[i].SelectedIndex = result.Id - 17;
            }
            else
            {
                allMotComboBox[i].SelectedIndex = 2;

            }
        }
        var error = _error.ReadErrorSettings()[0];

        phasesNumberValue.Text = $"{error.phaseNumber}-Phases";
        voltageNumberValue.Text = $"{error.phaseVoltage} V";
        gridValue.Text = $"{error.gridFreq}Hz";
        extPowerValue.Text = error.extPower ? "Yes" : "No";
        var config = _configration.ReadConfigrations()[0];
        i_neutValue.Text = config.i_neut.ToString("0.0");
        i_mot1Value.Text = config.i_mot1.ToString("0.0");
        i_mot2Value.Text = config.i_mot2.ToString("0.0");



    }
    private void OnPopupOverlayPointerPressed(object sender, PointerPressedEventArgs e)
    {
        targetText.Text = oldValue.ToString("0.0");
        keyBoardPopup.IsVisible = false;
    }
    private void OnKeyClick(object? sender, RoutedEventArgs e)
    {
        if (sender is Button button)
        {
            if (button.Content == ".")
            {
                if (Char.IsDigit(targetText.Text[0]) && !targetText.Text.Contains(button.Content.ToString()))
                {
                    targetText.Text += button.Content;

                }
            }
            else 
            {
                targetText.Text += button.Content;
                if (float.Parse(targetText.Text) > 20.0)
                {
                    targetText.Text = "20.0";
                }
            }
           
        }

    }
    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 void EnterClick(object? sender, RoutedEventArgs e)
    {
        var config = _configration.ReadConfigrations()[0];
        if (targetText.Name== "i_mot2Value")
        {
            config.i_mot2 = float.Parse(targetText.Text);
        }
        else if (targetText.Name == "i_mot1Value")
        {
            config.i_mot1 = float.Parse(targetText.Text);
        }
        else
        {
            config.i_neut = float.Parse(targetText.Text);
        }
        _configration.UpdateConfigration(config);
        setDefaultValues();
        _mainWindow.sendConfig = true;
        keyBoardPopup.IsVisible = false;


    }
    private void ShowNumberKeyBoard(object? sender, RoutedEventArgs e)
    {
        if (sender is Button button)
        {
            if (button.Name=="i_mot2")
            {
                targetText = i_mot2Value;
            }
            else if (button.Name == "i_mot1")
            {
                targetText = i_mot1Value;

            }
            else if (button.Name== "i_neut")
            {
                targetText = i_neutValue;

            }
            oldValue = float.Parse(targetText.Text);
            targetText.Text = "";
            keyBoardPopup.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 void InnerPopupPointerPressed(object? sender, PointerPressedEventArgs e)
    {
        e.Handled = 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 void setDefaultSettings()
    {
        _mainWindow.minimizeBtn.IsVisible = false;
        var stackPanel = _mainWindow.HomeTrack.Parent as StackPanel;


        //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 (_isDiag||_isSoftware)
        {
            if (_isDiag)
            {
                _mainWindow.DiagnosticsTrack.IsVisible = true;
                _mainWindow.DiagnosticsPolygon.Stroke = Avalonia.Media.Brushes.Black;

            }
            else if (_isSoftware)
            {
                _mainWindow.SoftwareTrack.IsVisible = true;
                _mainWindow.SoftwarePolygon.Stroke = Avalonia.Media.Brushes.Black;
            }
                _mainWindow.SettingTrack.IsVisible = false;
        }
        else
        {
            _mainWindow.DiagnosticsTrack.IsVisible = false;
            _mainWindow.SoftwareTrack.IsVisible = false;

            _mainWindow.SettingTrack.IsVisible = true;
            _mainWindow.SettingPolygon.Stroke = Avalonia.Media.Brushes.Black;
        }
        // Remove the button from its current position
        stackPanel.Children.Remove(_mainWindow.AdvanceSettingsTrack);

        // Add it back at the end of the StackPanel
        stackPanel.Children.Add(_mainWindow.AdvanceSettingsTrack);
        _mainWindow.AdvanceSettingsTrack.IsVisible = true;
        _mainWindow.AdvanceSettingsPolygon.Stroke = Brush.Parse("#A4275D");
      


        _mainWindow.TitleBtn.IsVisible = true;
        _mainWindow.Title.Text = "DR-62664A";
        //Set Footer
        _mainWindow.footerMsg.IsVisible = true;
        _mainWindow.footerMsg.Text = "Map Inputs And Outputs, And Set The Board Internal Values";
        _mainWindow.footerMsg.Foreground = Brush.Parse("#A4275D");
        _mainWindow.footer.Background = Brush.Parse("#f2f2f2");
        _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;
    }
}