using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml;
using Avalonia.Media;
using AvaloniaApplication1.DataBase;
using DaireApplication.DataBase;
using DaireApplication.Views;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace DaireApplication;

public partial class Admin : UserControl
{
    private MainWindow? _mainWindow;
    private UserTable? _currentUser;
    private MachineTable _machine;
    private ConfigrationTable _configration;
    private CancellationTokenSource _cancellationTokenSource;
    private bool _isLongPress = false;
    public Admin()
    {
        InitializeComponent();
        _machine = new MachineTable();
        _machine = _machine.ReadMachine();
    }
  
    public Admin(MainWindow mainWindow, UserTable currentUser)
    {
        _currentUser = currentUser;
        _mainWindow = mainWindow;
        _machine = new MachineTable();
        _machine = _machine.ReadMachine();
        _configration = new();

        InitializeComponent();
        setDefaultSettings();
        setDafaultValues();
        AttachHandlers(_mainWindow.logoBtn, AdvanceSettingsView);
        AttachHandlers(_mainWindow.UserName, CloseApplication);
        _mainWindow.minimizeBtn.Click += MinimizeButton_Click;
    }
    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));
            };
        }
    }
    private void MinimizeButton_Click(object? sender, RoutedEventArgs e)
    {
        _mainWindow.WindowState = Avalonia.Controls.WindowState.Minimized;
    }
    public static void CloseApplication(object? sender, RoutedEventArgs e)
    {
        var lifetime = Application.Current?.ApplicationLifetime as IClassicDesktopStyleApplicationLifetime;
        lifetime?.Shutdown(); // This should correctly shut down the application
    }
    public  void AdvanceSettingsView(object? sender, RoutedEventArgs e)
    {
        if (_mainWindow.ContentArea.Content== this )
        {
            _mainWindow.ContentArea.Content = new AdvanceSettings(_mainWindow);

        }

    }
    private async void changeValue(object? sender, RoutedEventArgs e)
    {
        if (sender is Button button)
        {
            var gridParent = button.Parent as Grid;
            var stack = gridParent.Children[1] as StackPanel;
            var targetText = stack.Children[0] as TextBlock;

            // Handle single click behavior (just increase or decrease by 1)
            int currentValue = int.TryParse(targetText.Text, out var value) ? value : 0;
            if (gridParent.Tag.ToString() != "pMint" && gridParent.Tag.ToString() != "aMint")
            {
                if (button.Content.ToString() == "+")
                {
                    targetText.Text = (currentValue + 1).ToString();
                }
                else
                {
                    if (currentValue>0)
                    {
                        targetText.Text = (currentValue - 1).ToString();

                    }
                }

            }
            else
            {
                if (button.Content.ToString() == "+")
                {
                    if (currentValue<0)
                    {
                        targetText.Text = (currentValue + 1).ToString();

                    }
                }
                else
                {
                    targetText.Text = (currentValue - 1).ToString();
                }
            }

            // Perform machine updates based on the tag
            MachineTable data = _machine.ReadMachine();
            data.Id = _machine.Id;

            if (gridParent.Tag.ToString() == "pMaxt")
                data.PumbMaxHeat = int.Parse(targetText.Text);
            else if (gridParent.Tag.ToString() == "pMint")
                data.PumbMinHeat = int.Parse(targetText.Text);
            else if (gridParent.Tag.ToString() == "tmt")
                data.TankMaxHeat = int.Parse(targetText.Text);
            else if (gridParent.Tag.ToString() == "pd")
                data.PumbDelay = int.Parse(targetText.Text);
            else if (gridParent.Tag.ToString() == "pht")
                data.PreHeatingTemp = int.Parse(targetText.Text);
            else if (gridParent.Tag.ToString() == "md")
                data.MixerDelay = int.Parse(targetText.Text);
            else if (gridParent.Tag.ToString() == "pouring")
                data.PouringDelay = int.Parse(targetText.Text);
            else if (gridParent.Tag.ToString() == "cooling")
                data.CoolingDelay = int.Parse(targetText.Text);
            else if (gridParent.Tag.ToString() == "heating")
                data.HeatingDelay = int.Parse(targetText.Text);
            else if (gridParent.Tag.ToString() == "aMaxt")
            {
                data.AbsMaxHeat = int.Parse(targetText.Text);
                var allConfigrations = _configration.ReadConfigrations();
                foreach (var item in allConfigrations)
                {
                    item.Max = (int)data.AbsMaxHeat;
                    _configration.UpdateConfigration(item);
                }
                _mainWindow.sendConfig = true;
            }
            else if (gridParent.Tag.ToString() == "aMint")
            {
                data.AbsMinHeat = int.Parse(targetText.Text);
                var coolingConfig = _configration.ReadConfigrationById("3");
                //var pumbConfig = _configration.ReadConfigrationById("4");
                coolingConfig.Min = (int)data.AbsMinHeat;
                _configration.UpdateConfigration(coolingConfig);
                //pumbConfig.Min = 0;
                //_configration.UpdateConfigration(pumbConfig);
                _mainWindow.sendConfig = true;
            }

            _machine.UpdateMachine(data);
            _mainWindow._machine = _machine.ReadMachine();
        }
        else if (sender is Border border)
        {
            Button button1 = this.FindControl<Button>(border.Tag.ToString());
            var gridParent = button1.Parent as Grid;
            var stack = gridParent.Children[1] as StackPanel;
            var targetText = stack.Children[0] as TextBlock;

            // Handle single click behavior (just increase or decrease by 1)
            int currentValue = int.TryParse(targetText.Text, out var value) ? value : 0;
            if (gridParent.Tag.ToString() != "pMint" && gridParent.Tag.ToString() != "aMint")
            {
                if (button1.Content.ToString() == "+")
                {
                    targetText.Text = (currentValue + 1).ToString();
                }
                else
                {
                    if (currentValue > 0)
                    {
                        targetText.Text = (currentValue - 1).ToString();

                    }
                }

            }
            else
            {
                if (button1.Content.ToString() == "+")
                {
                    if (currentValue < 0)
                    {
                        targetText.Text = (currentValue + 1).ToString();

                    }
                }
                else
                {
                    targetText.Text = (currentValue - 1).ToString();
                }
            }

            // Perform machine updates based on the tag
            MachineTable data = _machine.ReadMachine();
            data.Id = _machine.Id;

            if (gridParent.Tag.ToString() == "pMaxt")
                data.PumbMaxHeat = int.Parse(targetText.Text);
            else if (gridParent.Tag.ToString() == "pMint")
                data.PumbMinHeat = int.Parse(targetText.Text);
            else if (gridParent.Tag.ToString() == "tmt")
                data.TankMaxHeat = int.Parse(targetText.Text);
            else if (gridParent.Tag.ToString() == "pd")
                data.PumbDelay = int.Parse(targetText.Text);
            else if (gridParent.Tag.ToString() == "pht")
                data.PreHeatingTemp = int.Parse(targetText.Text);
            else if (gridParent.Tag.ToString() == "md")
                data.MixerDelay = int.Parse(targetText.Text);
            else if (gridParent.Tag.ToString() == "pouring")
                data.PouringDelay = int.Parse(targetText.Text);
            else if (gridParent.Tag.ToString() == "cooling")
                data.CoolingDelay = int.Parse(targetText.Text);
            else if (gridParent.Tag.ToString() == "heating")
                data.HeatingDelay = int.Parse(targetText.Text);
            else if (gridParent.Tag.ToString() == "aMaxt")
            {
                data.AbsMaxHeat = int.Parse(targetText.Text);
                var allConfigrations = _configration.ReadConfigrations();
                foreach (var item in allConfigrations)
                {
                    item.Max = (int)data.AbsMaxHeat;
                    _configration.UpdateConfigration(item);
                }
                _mainWindow.sendConfig = true;
            }
            else if (gridParent.Tag.ToString() == "aMint")
            {
                data.AbsMinHeat = int.Parse(targetText.Text);
                var coolingConfig = _configration.ReadConfigrationById("3");
                //var pumbConfig = _configration.ReadConfigrationById("4");
                coolingConfig.Min = (int)data.AbsMinHeat;
                _configration.UpdateConfigration(coolingConfig);
                //pumbConfig.Min = 0;
                //_configration.UpdateConfigration(pumbConfig);
                _mainWindow.sendConfig = true;
            }

            _machine.UpdateMachine(data);
            _mainWindow._machine = _machine.ReadMachine();
        }
    }

    // Handle holding event
    private async void OnLongRecipeClick(object? sender, RoutedEventArgs e)
    {
        if (e is HoldingRoutedEventArgs args)
        {
            if (args.HoldingState == HoldingState.Started)
            {
                _isLongPress = true;

                if (sender is Button button)
                {
                    var gridParent = button.Parent as Grid;
                    var stack = gridParent.Children[1] as StackPanel;
                    var targetText = stack.Children[0] as TextBlock;
                    await ChangeValueRapidly(button.Content.ToString()=="+", targetText); // Start rapid increase
                    args.Handled = true;
                }
                else if(sender is Border border)
                {
                    Button button1 = this.FindControl<Button>(border.Tag.ToString());

                    var gridParent = button1.Parent as Grid;
                    var stack = gridParent.Children[1] as StackPanel;
                    var targetText = stack.Children[0] as TextBlock;
                    await ChangeValueRapidly(button1.Content.ToString() == "+", targetText); // Start rapid increase
                    args.Handled = true;
                }
            }
            else if (args.HoldingState == HoldingState.Completed || args.HoldingState == HoldingState.Cancelled)
            {
                _isLongPress = false;

                // Stop the rapid value change when the holding is completed
                _cancellationTokenSource?.Cancel();
            }
        }
    }

    private async Task ChangeValueRapidly(bool isIncrease, TextBlock targetText)
    {
        // Start rapid value change when the button is held
        _cancellationTokenSource?.Cancel();  // Cancel any previous task
        _cancellationTokenSource = new CancellationTokenSource();
        var token = _cancellationTokenSource.Token;
        int currentValue = 0;

        while (!token.IsCancellationRequested)
        {
             currentValue = int.TryParse(targetText.Text, out var value) ? value : 0;

            if (targetText.Name!= "fountainMinTemp" && targetText.Name != "absMinTemp") 
            {
                if (isIncrease)
                {
                    targetText.Text = (currentValue + 1).ToString();
                }
                else
                {
                    if (currentValue>0)
                    {
                        targetText.Text = (currentValue -1).ToString();
                    }
                }
            }
            else
            {
                if (isIncrease)
                {
                    if (currentValue < 0)
                    {
                        targetText.Text = (currentValue + 1).ToString();

                    }
                }
                else
                {
                    targetText.Text = (currentValue - 1).ToString();
                }
            }
            await Task.Delay(150); // Change speed here
        }
    }


    private void setDafaultValues()
    {
        fountainMaxTemp.Text = _machine.PumbMaxHeat.ToString();
        tankMaxTemp.Text = _machine.TankMaxHeat.ToString();
        pumbDelay.Text = _machine.PumbDelay.ToString();
        mixerDelay.Text = _machine.MixerDelay.ToString();
        heatingPause.Text = _machine.HeatingDelay.ToString();
        coolingPause.Text = _machine.CoolingDelay.ToString();
        pouringPause.Text = _machine.PouringDelay.ToString();
        fountainMinTemp.Text=_machine.PumbMinHeat.ToString();
        absMaxTemp.Text= _machine.AbsMaxHeat.ToString();
        absMinTemp.Text= _machine.AbsMinHeat.ToString();
        preHeatingTemp.Text= _machine.PreHeatingTemp.ToString();
    }
    private void setDefaultSettings()
    {
        _mainWindow.minimizeBtn.IsVisible = true;
        //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;
        _mainWindow.DiagnosticsTrack.IsVisible = false;
        _mainWindow.AdvanceSettingsTrack.IsVisible = false;
        _mainWindow.SoftwareTrack.IsVisible = false;
        _mainWindow.SettingTrack.IsVisible = true;
        _mainWindow.SettingPolygon.Stroke = Brush.Parse("#A4275D"); ;
        _mainWindow.TitleBtn.IsVisible = false;
        //_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 = true;

    }
}