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");

            IObservable<EventPattern<MouseEventArgs>> dragMoves =
                from move in allMoves
                where Mouse.Captured == background
                select move;

            IObservable<EventPattern<MouseEventArgs>> allPositionEvents =
                Observable.Merge(downs, ups, dragMoves);

            IObservable<Point> dragPositions =
                from move in allPositionEvents
                select move.EventArgs.GetPosition(background);

            dragPositions.Subscribe(point => { line.Points.Add(point); });


            // Example 11-25
            IObservable<Point> smoothed =
                from points in dragPositions.Window(5, 2)
                from totals in points.Aggregate(
                  new { X = 0.0, Y = 0.0, Count = 0 },
                  (acc, point) => new { X = acc.X + point.X, Y = acc.Y + point.Y, Count = acc.Count + 1 })
                where totals.Count > 0
                select new Point(totals.X / totals.Count, totals.Y / totals.Count);

            smoothed.Subscribe(point => { smoothedLine.Points.Add(point); });
        }

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

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

    }
}
