using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Media;

namespace OcadMapLibrary {

	public class MapLineSegment : MapPathSegment {

		public MapLineSegment() {
		}

		public MapLineSegment(Point endPoint) {
			EndPoint = endPoint;
		}

		public override double GetLength(Point startPoint) {
			return Point.Subtract(EndPoint, startPoint).Length;
		}

		public override bool HasLength(Point startPoint) {
			double dist = Point.Subtract(EndPoint, startPoint).Length;
			if (dist > 0) {
				return true;
			}
			return false;
		}

		public override double GetAngleAtLength(Point startPoint, double length) {
			return GetAngle(startPoint);
		}

		public override double GetAngleAtStart(Point startPoint) {
			return GetAngle(startPoint);
		}

		public override double GetAngleAtEnd(Point startPoint) {
			return GetAngle(startPoint);
		}

		public override PathSegment GetPathSegment() {
			LineSegment segment = new LineSegment(EndPoint, true);
			return segment;
		}

		public override List<MapPathSegment> SplitAtLength(Point startPoint, double length) {
			List<MapPathSegment> result = new List<MapPathSegment>();
			if (length <= 0) {
				return result;
			}
			if (length >= GetLength(startPoint)) {
				result.Add(Clone());
				return result;
			}
			Point split = GetPointAtLength(startPoint, length).Value;
			MapLineSegment start = (MapLineSegment)Clone();
			start.EndPoint = split;
			MapLineSegment end = (MapLineSegment)Clone();
			end.EndPoint = EndPoint;
			result.Add(start);
			result.Add(end);
			return result;
		}

		public override List<MapLineSegment> Flatten(Point startPoint) {
			List<MapLineSegment> result = new List<MapLineSegment>();
			result.Add((MapLineSegment)Clone());
			return result;
		}

		public override MapPathSegment Clone() {
			MapLineSegment clone = new MapLineSegment();
			PopulateCloneBase(clone);
			return clone;
		}

		public double GetAngle(Point startPoint) {
			Vector dir = Point.Subtract(EndPoint, startPoint);
			if (dir.Length == 0) {
				return 0;
			}
			return Math.Atan2(dir.Y, dir.X);
		}

		public override Point? GetPointAtLength(Point startPoint, double length) {
			if (length < 0 || length > GetLength(startPoint)) {
				return null;
			}
			Vector dir = Point.Subtract(EndPoint, startPoint);
			if (dir.Length == 0) {
				return startPoint;
			}
			dir.Normalize();
			dir = Vector.Multiply(dir, length);
			return Point.Add(startPoint, dir);
		}

		public override void Reverse(Point oldStartPoint) {
			EndPoint = oldStartPoint;
		}

	}

}
