using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Platform;
using Avalonia.Platform.Storage;

namespace Slimak;

public partial class MainWindow : Window
{
    public static readonly StyledProperty<bool> IsEatingProperty =
        AvaloniaProperty.Register<MainWindow, bool>(nameof(IsEating),
            defaultBindingMode: BindingMode.TwoWay, defaultValue: false);
    public bool IsEating
    {
        get => GetValue(IsEatingProperty);
        set => SetValue(IsEatingProperty, value);
    }
    
    public MainWindow()
    {
        InitializeComponent();
        AddHandler(DragDrop.DropEvent, Drop);
    }

    protected override void OnLoaded(RoutedEventArgs e)
    {
        base.OnLoaded(e);
        using var res = AssetLoader.Open(new Uri("avares://Slimak/resources/Salata.png"));
        using var file = File.OpenWrite("Salata.png");
        res.CopyTo(file);
    }

    private void InputElement_OnPointerOver(object? sender, PointerPressedEventArgs e)
    {
        if (IsEating)
        {
            IsEating = false;
            Console.WriteLine("Stopped eating");
        }
    }
    
    private void Drop(object? sender, DragEventArgs e)
    {
        if(IsEating)
            return;
        
        Console.WriteLine("Drag and Drop");
        var data = e.Data;
        var draggedFiles = data.GetFiles();
        var storageItems = (draggedFiles ?? Array.Empty<IStorageItem>()).ToArray();
        Console.WriteLine($"files: {storageItems.Select(f => f.Name).Aggregate((a, b) => a + " " + b + " ")}");
        if(draggedFiles != null && storageItems.Any(st => st.Name.ToLower().Contains("salata")))
        {
            IsEating = true;
            Console.WriteLine("Started eating");
        }
    }
}