using Avalonia.Controls;
using Avalonia.Interactivity;
using Avalonia.Threading;
using Mlaumcherb.Client.Avalonia.сеть;

namespace Mlaumcherb.Client.Avalonia.зримое;

public partial class NetworkTaskView : UserControl
{
    public readonly NetworkTask Task;
    private readonly Action<NetworkTaskView> _removeFromList;


    public NetworkTaskView()
    {
        throw new Exception();
    }
    
    public NetworkTaskView(NetworkTask task, Action<NetworkTaskView> removeFromList)
    {
        Task = task;
        _removeFromList = removeFromList;
        InitializeComponent();
        NameText.Text = task.Name;
        StatusText.Text = task.DownloadStatus.ToString();
        task.OnStart += OnTaskOnStart;
        task.OnProgress += ReportProgress;
        task.OnStop += OnTaskStop;
    }

    private void OnTaskOnStart()
    {
        Dispatcher.UIThread.Invoke(() =>
        {
            StatusText.Text = Task.DownloadStatus.ToString();
        });
    }

    private void OnTaskStop(NetworkTask.Status status)
    {
        Dispatcher.UIThread.Invoke(() =>
        {
            StatusText.Text = status.ToString();
            if(!string.IsNullOrEmpty(ProgressText.Text))
            {
                int speedIndex = ProgressText.Text.IndexOf('(');
                if(speedIndex > 0)
                    ProgressText.Text = ProgressText.Text.Remove(speedIndex);
            }
        });
    }

    void ReportProgress(DownloadProgress progress)
    {
        Dispatcher.UIThread.Invoke(() =>
        {
            ProgressText.Text = progress.ToString();
        });
    }

    private void RemoveFromList(object? sender, RoutedEventArgs e)
    {
        Task.Cancel();
        Dispatcher.UIThread.Invoke(() => _removeFromList.Invoke(this));
    }
}
