using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows;
using System;
using Telerik.Windows.Controls.Map;
using Telerik.Windows.Controls;

namespace Demo.RadMap.UI.Tools
{
    public class MeasureTool : BaseMapTool
    {
        private MapLine currentMapLine;
        private MouseDragBehavior previousMapDragMode;
        private Point endPoint;
        private InformationLayer iLayer;
        private bool isDragging;
        private Point startPoint;

        public override void Connect(Telerik.Windows.Controls.RadMap map)
        {
            base.Connect(map);
            this.iLayer = map.FindChildByType<InformationLayer>();
            previousMapDragMode = map.MouseDragMode;
        }

        public void DrawTextOnMidPoint(MapLine line)
        {
            TextBlock tb = new TextBlock();

            tb.Foreground = new SolidColorBrush(Colors.Black);
            tb.Text = line.GetDistance().ToString("N4");

            MapLayer.SetLocation(tb, line.MidPoint());
            iLayer.Items.Add(tb);

            iLayer.InvalidateArrange();
        }

        protected override void MouseDown(object sender, MouseButtonEventArgs e)
        {
            map.MouseDragMode = MouseDragBehavior.None;
            isDragging = true;
            startPoint = e.GetPosition(map);
            e.Handled = true;
        }

        protected override void MouseMove(object sender, MouseEventArgs e)
        {
            if (isDragging)
            {
                endPoint = e.GetPosition(map);

                if (currentMapLine == null)
                {
                    currentMapLine = new MapLine();
                    iLayer.Items.Add(currentMapLine);
                }

                currentMapLine.Point1 = Location.GetCoordinates(map, startPoint);
                currentMapLine.Point2 = Location.GetCoordinates(map, endPoint);
                currentMapLine.StrokeThickness = 2.0;
                currentMapLine.Stroke = new SolidColorBrush(Colors.Red);

                iLayer.InvalidateArrange();
            }
        }

        protected override void MouseUp(object sender, MouseButtonEventArgs e)
        {
            e.Handled = true;

            //DrawLine();
            isDragging = false;
            DrawTextOnMidPoint(currentMapLine);
            currentMapLine = null;

            map.MouseDragMode = previousMapDragMode;
        }
    }
}
