using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace ChartSamples
{
  public partial class AngleSelector : UserControl
  {
    double _angle;
    RotateTransform _rt = new RotateTransform();
    Point cp = new Point();

    public event EventHandler AngleChanged;

    public AngleSelector()
    {
      InitializeComponent();
      line.RenderTransform = ar1.RenderTransform = ar2.RenderTransform = _rt;
    }

    protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e)
    {
      Point pt  = e.GetPosition(LayoutRoot);
      Angle = 180 / Math.PI * Math.Atan2(-(pt.Y - cp.Y), pt.X - cp.X);

      base.OnMouseLeftButtonUp(e);
    }

    public double Angle
    {
      get { return _angle; }
      set 
      {
        if (_angle != value)
        {
          _angle = value;
          _rt.Angle = -value;
          tb.Text = _angle.ToString("0");
          if (AngleChanged != null)
            AngleChanged(this, EventArgs.Empty);
          //Update(LayoutRoot.ActualWidth, LayoutRoot.ActualHeight);
        }
      }
    }

    void Update(double w, double h)
    {
      //double w = LayoutRoot.Width;
      //double h = LayoutRoot.Height;
      cp = new Point(0.5 * w, 0.5 * h);
      _rt.CenterX = cp.X; _rt.CenterY = cp.Y;

      double r = 0.4*Math.Min(w,h);
      el.Width = el.Height = 2*r;
      Canvas.SetLeft(el, cp.X - r);
      Canvas.SetTop(el, cp.Y - r);

      line.X1 = cp.X + r;
      line.Y1 = cp.Y;
      line.X2 = cp.X - r;
      line.Y2 = cp.Y;

      ar1.X1 = line.X1;
      ar1.Y1 = line.Y1;
      ar1.X2 = line.X1 - 0.6*r;
      ar1.Y2 = line.Y1 - 0.2*r;

      ar2.X1 = line.X1;
      ar2.Y1 = line.Y1;
      ar2.X2 = line.X1 - 0.6 * r;
      ar2.Y2 = line.Y1 + 0.2 * r;
    }

    protected override Size ArrangeOverride(Size finalSize)
    {
      //LayoutRoot.Width = finalSize.Width;
      //LayoutRoot.Height = finalSize.Height;
      Update(finalSize.Width, finalSize.Height);
      return base.ArrangeOverride(finalSize);
    }
  }
}
