using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.LogicalTree;
using Avalonia.Markup.Xaml;
using Avalonia.Media;
using DaireApplication.DataBase;
using DaireApplication.ViewModels;
using DaireApplication.Views;
using System;
using System.Collections.Generic;
using System.Reflection.PortableExecutable;

namespace DaireApplication;

public partial class ManualControl : UserControl
{
    private MainWindow? _mainWindow;
    bool isNegative = false;
    TextBlock targetText = new TextBlock();
    float oldValue = 0;
    public MachineTable _machine { get; set; }


    public ManualControl()
    {
        InitializeComponent();
    }
    public ManualControl(MainWindow mainWindow)
    {
        _mainWindow = mainWindow;
        _machine = new MachineTable();

        InitializeComponent();
        setDefaultSettings();
        getUiElementes();
    }
    private void setDefaultSettings()
    {
        _mainWindow.minimizeBtn.IsVisible = false;
        //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 = true;
        _mainWindow.RecipePanelPolygon.Stroke = Avalonia.Media.Brushes.Black;
        _mainWindow.RecipeEditTrack.IsVisible = false;
        _mainWindow.DiagnosticsTrack.IsVisible = false;
        _mainWindow.AdvanceSettingsTrack.IsVisible = false;
        _mainWindow.SoftwareTrack.IsVisible = false;
        _mainWindow.SettingTrack.IsVisible = false;
        _mainWindow.TitleBtn.IsVisible = false;
        _mainWindow.ManualControlTrack.IsVisible = true;
        _mainWindow.ManualControlPolygon.Stroke = Brush.Parse("#A4275D"); 
        //_mainWindow.Title.Text = _recipeTable.Name;

        //Set Footer
        _mainWindow.footerMsg.IsVisible = false;
        _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 = true;
        _mainWindow.version.IsVisible = false;
        _mainWindow.chefBtns.IsVisible = false;
    }

    private void ToggleMoldHeaterClick(object? sender, PointerPressedEventArgs e)
    {
        if (MoldHeaterStatus.Text == "ON")
        {
            _mainWindow.moldHeaterMotor = 0;
            //MoldHeaterStatus.Text = "OFF";
            //MoldHeaterUnderline.Fill = Brush.Parse("#666666");
        }
        else
        {
            _mainWindow.moldHeaterMotor = 1;
            //MoldHeaterStatus.Text = "ON";
            //MoldHeaterUnderline.Fill = Brush.Parse("#A4275D");
        }
    }

    private void ToggleVibrationClick(object? sender, PointerPressedEventArgs e)
    {
        if (VibrationStatus.Text == "ON")
        {
            _mainWindow.vibrationMotor = 0;
            //VibrationStatus.Text = "OFF";
            //VibrationUnderline.Fill = Brush.Parse("#666666");
        }
        else
        {
            _mainWindow.vibrationMotor = 1;
            //VibrationStatus.Text = "ON";
            //VibrationUnderline.Fill = Brush.Parse("#A4275D");
        }
    }

    private void ToggleVibHeaterClick(object? sender, PointerPressedEventArgs e)
    {
        if (VibHeaterStatus.Text == "ON")
        {
            _mainWindow.vibHeaterMotor = 0;
            //VibHeaterStatus.Text = "OFF";
            //VibHeaterUnderline.Fill = Brush.Parse("#666666");
        }
        else
        {
            _mainWindow.vibHeaterMotor = 1;
            //VibHeaterStatus.Text = "ON";
            //VibHeaterUnderline.Fill = Brush.Parse("#A4275D");
        }
    }

    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)
    {
        var tankBtm = _mainWindow._mapping.Find(x => x.Name.ToLower() == "Tank Bottom Temp".ToLower());
        var pumb = _mainWindow._mapping.Find(x => x.Name.ToLower() == "Pump Temp".ToLower());
        var fount = _mainWindow._mapping.Find(x => x.Name.ToLower() == "Fountain Temp".ToLower());
        List<int> setTempValues = new List<int>();
        setTempValues.AddRange([_mainWindow.holdingRegister.setTemp1, _mainWindow.holdingRegister.setTemp2, _mainWindow.holdingRegister.setTemp3, _mainWindow.holdingRegister.setTemp4]);
      
        if (sender is Button button)
        {
            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")
                {
                    foreach (var item in tankBtm.BitNumbers)
                    {
                        setTempValues[item - 8] = (int)(number * 10);
                    }
                    machine.setTemp1 = number;
                }
                else if (button.Tag.ToString() == "t3")
                {
                    foreach (var item in pumb.BitNumbers)
                    {
                        setTempValues[item - 8] = (int)(number * 10);
                    }
                    machine.setTemp3 = number;
                }
                else if (button.Tag.ToString() == "t4")
                {
                    foreach (var item in fount.BitNumbers)
                    {
                        setTempValues[item - 8] = (int)(number * 10);
                    }
                    machine.setTemp4 = number;
                }
                _mainWindow.holdingRegister.setTemp1 = setTempValues[0];
                _mainWindow.holdingRegister.setTemp2 = setTempValues[1];
                _mainWindow.holdingRegister.setTemp3 = setTempValues[2];
                _mainWindow.holdingRegister.setTemp4 = setTempValues[3];
                _machine.UpdateMachine(machine);
                getUiElementes();


                keyBoardPopup.IsVisible = false;
                await _mainWindow.WriteToSerialAsync("DiagnosticsEnter");
            }
        }
    }

    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 = setTankBtmText;
            }
            else if (border.Tag?.ToString() == "t3")
            {
                targetText = setHelixText;
            }
            else if (border.Tag?.ToString() == "t4")
            {
                targetText = setChocolateText;
            }
            enterBtn.Tag = border.Tag;

            isNegative = targetText.Text.StartsWith("-");
            var x = targetText.Text.Substring(1);

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

        }

    }

    private void getUiElementes()
    {
        var machine = _machine.ReadMachine();
        setTankBtmText.Text = char.IsDigit(machine.setTemp1.ToString()[0]) ? "+" + machine.setTemp1.ToString() : machine.setTemp1.ToString("0.0");
        setHelixText.Text = char.IsDigit(machine.setTemp3.ToString()[0]) ? "+" + machine.setTemp3.ToString() : machine.setTemp3.ToString("0.0");
        setChocolateText.Text = char.IsDigit(machine.setTemp4.ToString()[0]) ? "+" + machine.setTemp4.ToString() : machine.setTemp4.ToString("0.0");
    }
}