using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Documents;
using Avalonia.Controls.Shapes;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml;
using Avalonia.Media;
using AvaloniaApplication1.DataBase;
using DaireApplication.DataBase;
using DaireApplication.ViewModels;
using DaireApplication.Views;
using System;
using System.Drawing;
using System.Reflection.PortableExecutable;
using System.Threading;

namespace DaireApplication;

public partial class Settings : UserControl
{
    Button controllButton = new Button();
    private MainWindow? _mainWindow;
    private UserTable? _currentUser;
    public RecipeTable? _recipeTable;
    private MachineTable _machine;
    public string ActiveColor { get; set; } = "#A4275D";
    public string PassiveColor { get; set; } = "#666666";

    public Settings()
    {
        InitializeComponent();
    }
    public Settings(MainWindow mainWindow, UserTable currentUser,RecipeTable recipeTable)
    {
        _currentUser = currentUser;
        _mainWindow = mainWindow;
        _recipeTable = recipeTable;
        _machine = new MachineTable();
        _machine = _machine.ReadMachine();

        InitializeComponent();

        setDefaultSettings();

        setDafaultValues();
        mixerBtn.Click += _mainWindow.MotorClick;
        fountainBtn.Click += _mainWindow.FountainClick;
    }


    private void toggelOnOffClick(object? sender, RoutedEventArgs e)
    {
        if (sender is Button button)
        {
            var StackPanel = button.Content as StackPanel;
            var Label = StackPanel.Children;
            var underLine = Label[2] as Avalonia.Controls.Shapes.Rectangle;
            var titelLable = Label[0] as Label;
          
           
         
            if (Label[1] is Label targetLable)
            {
                if (targetLable.Content == "ON")
                {
                    if (titelLable.Content == "MOLD HEATER")
                    {
                        _mainWindow.moldHeaterMotor = 0;
                    }
                    if (titelLable.Content == "VIBRATION")
                    {
                        _mainWindow.vibrationMotor = 0;

                    }
                    if (titelLable.Content == "VIB. HEATER")
                    {
                        _mainWindow.vibHeaterMotor = 0;

                    }
                   

                }
                else
                {
                    if (titelLable.Content == "MOLD HEATER")
                    {
                        _mainWindow.moldHeaterMotor = 1;
                    }
                    if (titelLable.Content == "VIBRATION")
                    {
                        _mainWindow.vibrationMotor = 1;

                    }
                    if (titelLable.Content == "VIB. HEATER")
                    {
                        _mainWindow.vibHeaterMotor = 1;

                    }

                }
            }
        }

    } 
    private void PedalBtn(object? sender, RoutedEventArgs e)
    {
        if (sender is Button button)
        {
            var StackPanel = button.Content as StackPanel;
            var Label = StackPanel.Children;
            var underLine = Label[1] as Avalonia.Controls.Shapes.Rectangle;
            if (Label[0] is TextBlock targetLable)
            {
                if (targetLable.Text == "AUTO")
                {
                    if (_mainWindow.pedalOnTimer!=null )
                    {
                        _mainWindow.pedalOnTimer.Change(Timeout.Infinite, Timeout.Infinite);
                        _mainWindow.pedalOnTimer = null;
                        _mainWindow.pedalOnSeconds = 0;
                    }
                    if (_mainWindow.pedalOffTimer!=null)
                    {
                        _mainWindow.pedalOffTimer.Change(Timeout.Infinite, Timeout.Infinite);
                        _mainWindow.pedalOffTimer = null;
                        _mainWindow.pedalOffSeconds = 0;
                    }
                    _mainWindow.pedalMotor = 0;
                    targetLable.Text = "MANUAL";
                    underLine.Fill = Brush.Parse("#666666");
                    PedalAutoContainer.IsEnabled = false;
                    _recipeTable.Pedal = true;
                }
                else
                {
                    _mainWindow.pedalMotor = 1;
                    _mainWindow.pedalState = -1;
                    _mainWindow.setPedalTimerOnce = 1;
                    _mainWindow.pedalOnSeconds = 0;
                    _mainWindow.pedalOffSeconds = 0;
                    targetLable.Text = "AUTO";
                    underLine.Fill = Brush.Parse("#A4275D");
                    PedalAutoContainer.IsEnabled = true;
                    _recipeTable.Pedal = false;

                }
                _recipeTable.UpdateRecipe(_recipeTable);
            }
        }

    } 
    private void adjustPedalTime(object? sender, RoutedEventArgs e)
    {
        if (sender is Button button)
        {
            if (button.Classes[0].ToString()== "PedalOff")
            {
                if (button.Content == "−")
                {
                    if (Int32.Parse(PedalOffTime.Text) > 0)
                    {
                        PedalOffTime.Text = (Int32.Parse(PedalOffTime.Text) - 1).ToString();
                    }

                }
                else if (button.Content == "+")
                {

                    PedalOffTime.Text = (Int32.Parse(PedalOffTime.Text) + 1).ToString();
                }
                _recipeTable.PedalOffTime = Int32.Parse(PedalOffTime.Text);
                _recipeTable.UpdateRecipe(_recipeTable);
            }
            else
            {
                if (button.Content == "−")
                {
                    if (Int32.Parse(PedalOnTime.Text) > 0)
                    {
                        PedalOnTime.Text = (Int32.Parse(PedalOnTime.Text) - 1).ToString();
                    }

                }
                else if (button.Content == "+")
                {
                    if (int.TryParse(PedalOnTime.Text, out int value))
                    {
                        if (value < 9)
                        {
                            PedalOnTime.Text = (value + 1).ToString();
                        }
                    }
                }
                _recipeTable.PedalOnTime = Int32.Parse(PedalOnTime.Text);
                _recipeTable.UpdateRecipe(_recipeTable);
            }
                _recipeTable = _recipeTable.ReadRecipesById(_recipeTable.Id.ToString());

        }

    }

    private async void OnIgnorePopupOverlayPointerPressed(object? sender, RoutedEventArgs e)
    {
        DeletePopupOverlay.IsVisible = false;



    } 
    private async void HideTempErrorPopUp(object? sender, RoutedEventArgs e)
    {
        _mainWindow.pauseTimer = false;
        _mainWindow.pauseTempTracking = false; // Allow process to continue after clicking "No"
        _mainWindow.tempWarningAccepted = true; // User accepted the temperature warning
        tempErrorPopupOverlay.IsVisible = false;
    }
    private async void YesBtnClick(object? sender, RoutedEventArgs e)
    {
        if (sender is Button button)
        {
            if (DeletePopupOverlay.Tag=="home")
            {

                _mainWindow.resetAll();
                // rest the board
                _mainWindow.restBoard = true;
                _mainWindow.UserName.Content = "Select User";
                _mainWindow.footerMsg.Text = "";
                _mainWindow.ContentArea.Content = new Home(_mainWindow);
            }
            else if (DeletePopupOverlay.Tag == "recipeSel")
            {
                _mainWindow.resetAll();
                // rest the board
                _mainWindow.restBoard = true;
                _mainWindow.footerMsg.Text = "";
                _mainWindow.ContentArea.Content = new Recipe(_mainWindow, Program.currentUser);
            }
        }
      


    } 
    private async void ErrorYesBtnClick(object? sender, RoutedEventArgs e)
    {
        if (sender is Button button)
        {
            //_mainWindow.pause = true;
            //_mainWindow.pauseTempTracking = true;
            //_mainWindow.pauseTimer = true;

            // stop the recipe
            _mainWindow.startRecipe = 0;
            _mainWindow.Heating = 0;
            _mainWindow.cooling = 0;
            _mainWindow.pouring = 0;
            _mainWindow.PumbOn = -1;
            _mainWindow.pedalMotor = -1;
            if (_mainWindow.heatingTimer != null)
            {
                _mainWindow.heatingTimer.Change(Timeout.Infinite, Timeout.Infinite);
                _mainWindow.heatingSeconds = 0;
            }
            if (_mainWindow.coolingTimer != null)
            {
                _mainWindow.coolingTimer.Change(Timeout.Infinite, Timeout.Infinite);
                _mainWindow.coolingSeconds = 0;
            }
            if (_mainWindow.pouringTimer != null)
            {
                _mainWindow.pouringTimer.Change(Timeout.Infinite, Timeout.Infinite);
                _mainWindow.pouringSeconds = 0;
            }
            var fount = _mainWindow._mapping.Find(x => x.Name.ToLower() == "Pump".ToLower());
            if (fount != null)
            {
                if (fount.BitNumbers.Count > 0)
                {
                    foreach (var bit in fount.BitNumbers)
                    {

                        _mainWindow.holdingRegister.motor &= (ushort)~(1 << bit);
                    }
                }
            }
            _mainWindow.holdingRegister.setTemp1 = -10000;
            _mainWindow.holdingRegister.setTemp2 = -10000;
            _mainWindow.holdingRegister.setTemp3 = -10000;
            _mainWindow.holdingRegister.setTemp4 = -10000;
            await _mainWindow.WriteToSerialAsync("ErrorYesBtnClick");
            tempErrorPopupOverlay.IsVisible = false;
            _mainWindow.footerMsg.Text = "Recipe Stoped";
            _mainWindow.recipeStartBtn.Content = "START RECIPE";
        }
    }



    private void setDefaultSettings()
    {
        //Set Track Up
        _mainWindow.HomeTrack.IsVisible = true;
        //_mainWindow.HomePolygon.Stroke = Avalonia.Media.Brushes.Black;
        _mainWindow.RecipeSelTrack.IsVisible = true;
        _mainWindow.RecipeSelPolygon.Stroke = Avalonia.Media.Brushes.Black;
        _mainWindow.RunInterfaceTrack.IsVisible = true;
        _mainWindow.RunInterfacePolygon.Stroke = Brush.Parse("#A4275D");
        _mainWindow.RecipePanelTrack.IsVisible = false;
        _mainWindow.RecipeEditTrack.IsVisible = false;
        _mainWindow.SettingTrack.IsVisible = false;
        _mainWindow.DiagnosticsTrack.IsVisible = false;
        _mainWindow.TitleBtn.IsVisible = true;
        _mainWindow.Title.Text = _recipeTable.Name;

        //Set Footer
        _mainWindow.footerMsg.Text = "Ready";
        _mainWindow.footerMsg.MaxWidth = 500;
        _mainWindow.footer.Background = Avalonia.Media.Brushes.WhiteSmoke;
        _mainWindow.footerMsg.Foreground = Avalonia.Media.Brushes.Green;
        _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 = true;
        _mainWindow.adminBtns.IsVisible = false;
    } 
    private void setDafaultValues()
    {
        //Recipe Settings
        heatingValue.Content = _recipeTable.HeatingGoal;
        coolingValue.Content = _recipeTable.CoolingGoal;
        pouringValue.Content = _recipeTable.PouringGoal;
        //tankTemp
        TankTempValue.Content = _recipeTable?.TankTemp;
        //mixer
        var mixerChildren= MixerSP.Children;
        var mixerLable = mixerChildren[1] as Label;
        mixerLable.Content = _recipeTable.Mixer.Value ? "ON" : "OFF";
        var mixerUnderLine = mixerChildren[2] as Avalonia.Controls.Shapes.Rectangle;
        mixerUnderLine.Fill = _recipeTable.Mixer.Value ? Brush.Parse(ActiveColor) : Brush.Parse(PassiveColor);
        //pedal
        var pedalChildren = PedalSP.Children;
        var pedalText = pedalChildren[0] as TextBlock;
        var pedalUnderLine = pedalChildren[1] as Avalonia.Controls.Shapes.Rectangle;
        if (_recipeTable.Pedal.Value)
        {
            pedalText.Text = "MANUAL";
            pedalUnderLine.Fill =    Brush.Parse(PassiveColor);
            PedalAutoContainer.IsEnabled = false;
        }
        else
        {
            pedalText.Text = "AUTO";
            pedalUnderLine.Fill = Brush.Parse(ActiveColor);
            PedalAutoContainer.IsEnabled = true;
        }
        PedalOffTime.Text = _recipeTable.PedalOffTime.ToString();
        PedalOnTime.Text = _recipeTable.PedalOnTime.ToString();
        //fountain Temp
        FountainTempValue.Content = _recipeTable?.FountainTemp;
        //fountain
        var fountainChildren = FountainSP.Children;
        var fountainLable = fountainChildren[1] as Label;
        fountainLable.Content = _recipeTable.Fountain.Value ? "ON" : "OFF";
        var fountainUnderLine = fountainChildren[2] as Avalonia.Controls.Shapes.Rectangle;
        fountainUnderLine.Fill = _recipeTable.Fountain.Value ? Brush.Parse(ActiveColor) : Brush.Parse(PassiveColor);
        //mold Heater
        var moldHeaterChildren = MoldHeaterSP.Children;
        var moldHeaterLable = moldHeaterChildren[1] as Label;
        moldHeaterLable.Content = _recipeTable.MoldHeater.Value ? "ON" : "OFF";
        var moldHeaterUnderLine = moldHeaterChildren[2] as Avalonia.Controls.Shapes.Rectangle;
        moldHeaterUnderLine.Fill = _recipeTable.MoldHeater.Value ? Brush.Parse(ActiveColor) : Brush.Parse(PassiveColor);
        // vibration
        var vibrationChildren = VibrationSP.Children;
        var vibrationLable = vibrationChildren[1] as Label;
        vibrationLable.Content = _recipeTable.Vibration.Value ? "ON" : "OFF";
        var vibrationUnderLine = vibrationChildren[2] as Avalonia.Controls.Shapes.Rectangle;
        vibrationUnderLine.Fill = _recipeTable.Vibration.Value ? Brush.Parse(ActiveColor) : Brush.Parse(PassiveColor);
        // vib heater
        var vibHeaterChildren = VibHeaterSP.Children;
        var vibHeaterLable = vibHeaterChildren[1] as Label;
        vibHeaterLable.Content = _recipeTable.VibHeater.Value ? "ON" : "OFF";
        var vibHeaterUnderLine = vibHeaterChildren[2] as Avalonia.Controls.Shapes.Rectangle;
        vibHeaterUnderLine.Fill = _recipeTable.VibHeater.Value ? Brush.Parse(ActiveColor) : Brush.Parse(PassiveColor);


    }
}