using System;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Minint.Controls;
using Minint.ViewModels;

namespace Minint.Views;

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    protected override void OnOpened(EventArgs e)
    {
        base.OnOpened(e);

        var canvas = this.FindControl<PixelCanvas>("Canvas");
        var hScroll = this.FindControl<ScrollBar>("HScroll");
        var vScroll = this.FindControl<ScrollBar>("VScroll");

        if (canvas is not null && hScroll is not null && vScroll is not null)
            canvas.AttachScrollBars(hScroll, vScroll);

        if (canvas is not null && DataContext is MainWindowViewModel vm)
            WireCanvasEvents(canvas, vm.Editor);
    }

    protected override void OnDataContextChanged(EventArgs e)
    {
        base.OnDataContextChanged(e);
        if (DataContext is MainWindowViewModel vm)
            vm.Owner = this;
    }

    private static void WireCanvasEvents(PixelCanvas canvas, EditorViewModel editor)
    {
        canvas.Editor = editor;

        canvas.ToolDown += (px, py) => editor.OnToolDown(px, py);
        canvas.ToolDrag += (px, py) => editor.OnToolDrag(px, py);
        canvas.CursorPixelChanged += pixel => editor.PreviewCenter = pixel;
        canvas.GetPreviewMask = () => editor.GetPreviewMask();

        canvas.SelectionStart += (px, py) => editor.BeginSelection(px, py);
        canvas.SelectionUpdate += (px, py) => editor.UpdateSelection(px, py);
        canvas.SelectionEnd += (px, py) => { editor.FinishSelection(px, py); canvas.InvalidateVisual(); };

        canvas.PasteMoved += (px, py) => editor.MovePaste(px, py);
        canvas.PasteCommitted += () => { editor.CommitPaste(); canvas.InvalidateVisual(); };
        canvas.PasteCancelled += () => { editor.CancelPaste(); canvas.InvalidateVisual(); };
    }
}
