using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reactive;
using System.Reactive.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace RxScribble
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            IObservable<EventPattern<MouseEventArgs>> downs =
                Observable.FromEventPattern<MouseEventArgs>(background, "MouseDown");
            IObservable<EventPattern<MouseEventArgs>> ups =
                Observable.FromEventPattern<MouseEventArgs>(background, "MouseUp");
            IObservable<EventPattern<MouseEventArgs>> allMoves =
                Observable.FromEventPattern<MouseEventArgs>(background, "MouseMove");

            // Listing 11-21
            var dragPointSets = from mouseDown in downs
                                join move in allMoves
                                  on ups equals allMoves into m
                                select m.Select(e => e.EventArgs.GetPosition(background));

            dragPointSets.Subscribe(dragPoints =>
            {
                var currentLine = new Polyline { Stroke = Brushes.Black, StrokeThickness = 2 };
                background.Children.Add(currentLine);

                dragPoints.Subscribe(point =>
                {
                    currentLine.Points.Add(point);
                });
            });


            // Te kod sprawdza kod z listingu 11-22 (patrz poniżej)
            dragPointSets
                .SelectMany(AverageX)
                .Subscribe(x => Debug.WriteLine("Average X for this drag operation: " + x));
        }

        // Listing 11-22
        static IObservable<double> AverageX(IObservable<Point> points)
        {
            return points.Select(p => p.X).Average();
        }

        // Listing 11-17
        private void OnBackgroundMouseDown(object sender, MouseButtonEventArgs e)
        {
            background.CaptureMouse();
        }

        private void OnBackgroundMouseUp(object sender, MouseButtonEventArgs e)
        {
            if (Mouse.Captured == background)
            {
                background.ReleaseMouseCapture();
            }
        }

    }
}
