using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using Telerik.Windows.Diagrams.Core;

namespace ConnectionManipulation
{
    public class MyRoutingService : RoutingService
    {
        public bool IsManipulation { get; set; }

        public MyRoutingService(IGraphInternal graph)
            : base(graph)
        {
        }

        public override ConnectionRoute FindExtendedRoute(IConnection connection)
        {
            var result = base.FindExtendedRoute(connection);
            if (!this.IsManipulation)
            {
                for (int i = 0; i < result.Points.Count - 1; i++)
                {
                    var current = result.Points[i];
                    var next = result.Points[i + 1];
                    bool isMiddle = false;
                    if (i > 0)
                    {
                        var prev = result.Points[i - 1];
                        if (prev.X == current.X && current.X == next.X)
                        {
                            isMiddle = true;
                            result.Points[i] = new Point(current.X, MainWindow.Middle(prev.Y, next.Y));
                        }
                        else if (prev.Y == current.Y && current.Y == next.Y)
                        {
                            isMiddle = true;
                            result.Points[i] = new Point(MainWindow.Middle(prev.X, next.X), current.Y);
                        }
                    }

                    if (!isMiddle)
                    {
                        if (current.X == next.X && (i + 2 > result.Points.Count - 1 || result.Points[i + 2].X != next.X))
                        {
                            result.Points.Insert(i + 1, new Point(current.X, MainWindow.Middle(current.Y, next.Y)));
                            i ++;
                        }
                        else if (current.Y == next.Y && (i + 2 > result.Points.Count - 1 || result.Points[i + 2].Y != next.Y))
                        {
                            result.Points.Insert(i + 1, new Point(MainWindow.Middle(current.X, next.X), current.Y));
                            i ++;
                        }
                    }
                }
            }
            return result;
        }

        public override System.Collections.Generic.IList<Point> FindRoute(IConnection connection)
        {
            return base.FindRoute(connection);
        }
    }
}
