package layoutgraph

import (
	
	

	

	
	
)

const edgeStrokeWidth = 3.0

type Edge struct {
	D2ID   *string
	ID     EntityID
	From   *Node
	To     *Node
	Points []*geo.Point

	SourceArrowhead      Arrowhead
	TargetArrowhead      Arrowhead
	SourceArrowheadLabel *Label
	TargetArrowheadLabel *Label

	MinWidth        int
	MinHeight       int
	Label           *Label
	LabelPercentage float64
	IsCurve         bool

	// edges between SQL Table shapes
	FromTableColumnIndex *int
	ToTableColumnIndex   *int

	IsInvisible bool
	Style       EdgeStyle

	// hierarchyRankWeight is transient metadata used only by the temporary
	// simple DAG passed to hierarchy ranking. Ordinary layout edges keep the
	// zero-value unset state and therefore use unit weight.
	hierarchyRankWeight    int
	hierarchyRankWeightSet bool
}

func ( *Edge) ( *Edge) bool {
	return .stylesMatchOneWay() && .stylesMatchOneWay()
}

func ( *Edge) ( *Edge) bool {
	if .Style.Opacity != nil {
		if !(.Style.Opacity != nil && .Style.Opacity.Value == .Style.Opacity.Value) {
			return false
		}
	}
	if .Style.Stroke != nil {
		if !(.Style.Stroke != nil && .Style.Stroke.Value == .Style.Stroke.Value) {
			return false
		}
	}
	if .Style.StrokeWidth != nil {
		if !(.Style.StrokeWidth != nil && .Style.StrokeWidth.Value == .Style.StrokeWidth.Value) {
			return false
		}
	}
	if .Style.StrokeDash != nil {
		if !(.Style.StrokeDash != nil && .Style.StrokeDash.Value == .Style.StrokeDash.Value) {
			return false
		}
	}
	if .Style.Animated != nil {
		if !(.Style.Animated != nil && .Style.Animated.Value == .Style.Animated.Value) {
			return false
		}
	}

	return true
}

func (,  *Node) *Edge {
	return &Edge{
		From:   ,
		To:     ,
		Points: []*geo.Point{},
	}
}

func ( *Edge) () bool {
	if ,  := .From.Graph.NodeToTree[.From];  {
		return true
	}
	if ,  := .To.Graph.NodeToTree[.To];  {
		return true
	}
	return false
}

func ( *Edge) () *geo.Point {
	if len(.Points) == 0 {
		return nil
	}
	return .Points[0]
}

func ( *Edge) () *geo.Point {
	if len(.Points) == 0 {
		return nil
	}
	return .Points[len(.Points)-1]
}

func ( *Edge) () EntityID {
	if  == nil {
		return 0
	}
	return .ID
}

func ( *Edge) () bool {
	return .From == .To
}

func ( *Edge) () bool {
	return .SourceArrowhead != "" &&
		.SourceArrowhead != NoArrowhead
}

func ( *Edge) () bool {
	return .TargetArrowhead != "" &&
		.TargetArrowhead != NoArrowhead
}

func ( *Edge) () bool {
	return .HasSourceArrow() != .HasTargetArrow()
}

func ( *Edge) () bool {
	return .HasSourceArrow() && .HasTargetArrow()
}

func ( *Edge) () bool {
	return !.HasSourceArrow() && !.HasTargetArrow()
}

// directedEndpoints returns the semantic source and target of a directed edge.
// Edge.From and Edge.To preserve declaration order, so a source-arrow-only edge
// points from To to From.
func ( *Edge) () (,  *Node,  bool) {
	if  == nil || !.isDirected() {
		return nil, nil, false
	}
	if .HasSourceArrow() {
		return .To, .From, true
	}
	return .From, .To, true
}

func ( *Edge) () bool {
	return .SourceArrowhead == .TargetArrowhead
}

func ( *Edge) ( *Edge) bool {
	if .SourceArrowhead == .SourceArrowhead && .TargetArrowhead == .TargetArrowhead {
		return true
	}
	if .SourceArrowhead == .TargetArrowhead && .TargetArrowhead == .SourceArrowhead {
		return true
	}
	return false
}

func ( *Edge) ( *Node) bool {
	return ( == .From && .HasSourceArrow()) || ( == .To && .HasTargetArrow())
}

func ( *Edge) ( *Node) Arrowhead {
	if  == .From {
		return .SourceArrowhead
	} else {
		return .TargetArrowhead
	}
}

func ( *Edge) () string {
	 := "-"
	if .HasSourceArrow() {
		 = "<" + 
	}
	if .HasTargetArrow() {
		 += ">"
	}
	if !.HasSourceArrow() && !.HasTargetArrow() {
		 += "-"
	}
	 := .From.DebugID()
	if .FromTableColumnIndex != nil {
		 = fmt.Sprintf("%s[%d]", , *.FromTableColumnIndex)
	}
	 := .To.DebugID()
	if .ToTableColumnIndex != nil {
		 = fmt.Sprintf("%s[%d]", , *.ToTableColumnIndex)
	}
	 := ""
	if .Label != nil {
		 = ": " + .Label.Text
	}
	return fmt.Sprintf("%s %s %s%s", , , , )
}

func ( *Edge) () bool {
	return .FromTableColumnIndex != nil && .ToTableColumnIndex != nil
}

func ( *Edge) () bool {
	return .FromTableColumnIndex != nil || .ToTableColumnIndex != nil
}

func ( *Edge) () bool {
	return .From.Cluster != nil || .To.Cluster != nil
}

func ( *Edge) () float64 {
	return .From.distance(.To, true)
}

func ( *Edge) () int {
	// One point for source and one for target centers = 2 for a straight line
	return len(.Points) - 1
}

// reconnect takes care of reassigning an edge
// 1. Update the other endpoint's adjacent nodes to replace old one with new
// 2. Update the new endpoint's adjacent nodes to include the other endpoint
// 3. Remove the other endpoint from the old endpoint's adjacent nodes
// 4. Reassign the edge pointers
func ( *Edge) ( *Node,  bool) {
	if  {
		.To.removeEdge()
		.addEdge()

		.To = 
	} else {
		.From.removeEdge()
		.addEdge()

		.From = 
	}
}

// isAxisAligned checks if the connected ends are axis aligned
// Test is to draw a line through the center and see if it overlaps
func ( *Edge) () bool {
	if .From == nil || .To == nil {
		return false
	}

	if .hasTableColumn() {
		 := .facingTablePorts(nil, nil)
		if .hasFrom && .hasTo {
			if geo.PrecisionCompare(.from.Y, .to.Y, AxisAlignmentTolerance) == 0 {
				return true
			}
		} else if .hasFrom {
			if geo.PrecisionCompare(.from.Y, .To.TopLeft.Y+.To.Height/2, AxisAlignmentTolerance) == 0 {
				return true
			}
		} else if .hasTo {
			if geo.PrecisionCompare(.to.Y, .From.TopLeft.Y+.From.Height/2, AxisAlignmentTolerance) == 0 {
				return true
			}
		} else if geo.PrecisionCompare(.From.TopLeft.X, .To.TopLeft.X, AxisAlignmentTolerance) == 0 {
			// if the tables are stacked, consider them aligned one of the sides is aligned
			return true
		} else if geo.PrecisionCompare(.From.TopLeft.X+.From.Width, .To.TopLeft.X+.To.Width, AxisAlignmentTolerance) == 0 {
			// if the tables are stacked, consider them aligned one of the sides is aligned
			return true
		}
		return false
	}

	// Horizontal alignment
	if geo.PrecisionCompare(.From.TopLeft.Y+.From.Height/2, .To.TopLeft.Y+.To.Height/2, AxisAlignmentTolerance) == 0 {
		return true
	}

	// Vertical alignment
	if geo.PrecisionCompare(.From.TopLeft.X+.From.Width/2, .To.TopLeft.X+.To.Width/2, AxisAlignmentTolerance) == 0 {
		return true
	}

	return false
}

func ( *Edge) ( *Edge) bool {
	if .To == .To && .From == .From {
		return true
	}
	if .From == .To && .To == .From {
		return true
	}

	return false
}

func ( *Edge) ( []*Edge) bool {
	for ,  := range  {
		if .isDuplicateOf() {
			return true
		}
	}
	return false
}

type Edges []*Edge

// return map to lookup the edges connected to each port of the node
func ( Edges) ( *Node) map[geo.Point][]*Edge {
	 := make(map[geo.Point][]*Edge)
	for ,  := range  {
		var  *geo.Point
		switch {
		case .From == :
			 = .SourcePort()
		case .To == :
			 = .TargetPort()
		default:
			continue
		}

		if  == nil {
			continue
		}

		if ,  := [*]; ! {
			[*] = make([]*Edge, 0)
		}
		[*] = append([*], )
	}
	return 
}

func ( *Edge) () float64 {
	return geo.Route(.Points).Length()
}

// LabelTopLeft returns the top-left point for a label of the given size and
// position on edge.
func ( *Edge) ( label.Position, ,  float64) *geo.Point {
	,  := .GetPointOnRoute(
		.Points,
		edgeStrokeWidth,
		.LabelPercentage,
		,
		,
	)
	return 
}

func ( *Edge) () (*geo.Point, *geo.Point) {
	,  := .boundingBoxValues()
	return &, &
}

func ( *Edge) () (geo.Point, geo.Point) {
	 := geo.Point{X: math.Inf(1), Y: math.Inf(1)}
	 := geo.Point{X: math.Inf(-1), Y: math.Inf(-1)}

	for ,  := range .Points {
		.X = math.Min(.X, .X)
		.Y = math.Min(.Y, .Y)
		.X = math.Max(.X, .X)
		.Y = math.Max(.Y, .Y)
	}

	if .Label != nil && len(.Points) != 0 && .Label.Position != label.Unset {
		 := .LabelTopLeft(.Label.Position, .Label.Width, .Label.Height)
		.X = math.Min(.X, .X)
		.Y = math.Min(.Y, .Y)
		.X = math.Max(.X, .X+.Label.Width)
		.Y = math.Max(.Y, .Y+.Label.Height)
	}
	if len(.Points) > 0 {
		if  := .SourceArrowheadLabel;  != nil {
			 := labelgeom.ArrowheadTopLeft(
				.Points,
				false,
				string(.SourceArrowhead),
				string(.TargetArrowhead),
				.Width,
				.Height,
			)
			.X = math.Min(.X, .X)
			.Y = math.Min(.Y, .Y)
			.X = math.Max(.X, .X+.Width)
			.Y = math.Max(.Y, .Y+.Height)
		}
		if  := .TargetArrowheadLabel;  != nil {
			 := labelgeom.ArrowheadTopLeft(
				.Points,
				true,
				string(.SourceArrowhead),
				string(.TargetArrowhead),
				.Width,
				.Height,
			)
			.X = math.Min(.X, .X)
			.Y = math.Min(.Y, .Y)
			.X = math.Max(.X, .X+.Width)
			.Y = math.Max(.Y, .Y+.Height)
		}
	}

	.X = math.Round(.X)
	.Y = math.Round(.Y)
	.X = math.Round(.X)
	.Y = math.Round(.Y)
	return , 
}

func ( *Edge) ( *Node) bool {
	return .hasArrowTo()
}

type EdgeSegment struct {
	geo.Segment
	edge *Edge
}

// For each axes:
// 1. For every edge segment of the axis, get its range of movement
// ---- The range of movement: the lower and upper bounds of where it can move
// ---- The considerations for bounds are node borders and locked in segments
// 2. Get the smallest range of movement, and group it with other edges that overlap and share the same range.
// 3. Evenly distribute the edges within its range of motion. They are now locked in.
// NOTE: Moving them may change the relative order of the edges.
// 4. Repeat from 1 until all edges locked in

// These two share the same range of movement (the left and right ends of the top node)
// .    ┌────────────────┐
// .    │                │
// .    │                │
// .    └──┬─────────────┘
// .       │   ▲
// .       │   │
// .       │   │
// .       │   │
// .       │   │
// .       │   │
// .       │   │
// .       │   │
// .       ▼   │
// . ┌─────────┴──────────────┐
// . │                        │
// . │                        │
// . └────────────────────────┘
//
// These two vertical segments do *not* share range of movement, since the bottom one has a higher floor.
// . ┌───────┐
// . │       │
// . │       │◄─────────────────┐
// . │       │                  │
// . │       │                  │
// . └───────┘                  │
// .                            │        ┌────────────────────────┐
// .                            │        │                        │
// .                            │        │                        │
// .                            │        │                        │
// .                            │        │                        │
// .  ┌──────┐                  │        │                        │
// .  │      │                  │        │                        │
// .  │      │◄─────────────────┼──┐     │                        │
// .  │      │                  │  │     │                        │
// .  └──────┘                  │  │     │                        │
// .                            │  │     │                        │
// .                            │  │     │                        │
// .  ┌──────┐                  │  │     │                        │
// .  │      ├──────────────────┘  │     │                        │
// .  │      │                     │     │                        │
// .  └──────┘     ┌──────┐        │     │                        │
// .               │      │        │     │                        │
// .               │      │        │     │                        │
// .               │      │        │     │                        │
// .               └──────┘        │     │                        │
// .                               │     │                        │
// .                               │     │                        │
// .                               │     └────────────────────────┘
// .  ┌───────┐                    │
// .  │       │                    │
// .  │       ├────────────────────┘
// .  │       │
// .  └───────┘
type facingTablePortValues struct {
	from        geo.Point
	to          geo.Point
	hasFrom     bool
	hasTo       bool
	orientation geo.Orientation
}

// facingTablePorts returns the ports related to the connected tables
// if they are properly aligned, without allocating points. If one table is on
// top of the other, there's no way to choose the proper direction and then
// there are no ports to return.
func ( *Edge) (,  *Node) facingTablePortValues {
	if !.hasTableColumn() {
		return facingTablePortValues{orientation: geo.NONE}
	}
	 := .From
	if  != nil {
		 = 
	}
	 := .To
	if  != nil {
		 = 
	}
	 := .orientation()
	 := facingTablePortValues{orientation: }
	switch  {
	case geo.TopLeft, geo.BottomLeft, geo.Left:
		if .FromTableColumnIndex != nil {
			.from, .hasFrom = .tableColumnPortValue(geo.Right, *.FromTableColumnIndex)
		}
		if .ToTableColumnIndex != nil {
			.to, .hasTo = .tableColumnPortValue(geo.Left, *.ToTableColumnIndex)
		}
		return 
	case geo.Right, geo.TopRight, geo.BottomRight:
		if .FromTableColumnIndex != nil {
			.from, .hasFrom = .tableColumnPortValue(geo.Left, *.FromTableColumnIndex)
		}
		if .ToTableColumnIndex != nil {
			.to, .hasTo = .tableColumnPortValue(geo.Right, *.ToTableColumnIndex)
		}
		return 
	}
	return facingTablePortValues{orientation: geo.NONE}
}

func ( *Edge) () bool {
	return (.SourceArrowheadLabel != nil && len(.SourceArrowheadLabel.Text) > 3) ||
		(.TargetArrowheadLabel != nil && len(.TargetArrowheadLabel.Text) > 3)
}

func ( *Edge) () bool {
	 := .Points[0]
	 := .Points[1]
	for  := 2;  < len(.Points); ++ {
		if orientation(, , .Points[]) != 0 {
			return false
		}
		 = 
		 = .Points[]
	}
	return true
}

func ( *Edge) () bool {
	 := .Points[0]
	 := .Points[len(.Points)-1]

	for ,  := range .From.Edges {
		if  ==  {
			continue
		}

		if nonNilEquals(.Points[0], ) || nonNilEquals(.Points[len(.Points)-1], ) {
			return true
		}
	}
	for ,  := range .To.Edges {
		if  ==  {
			continue
		}

		if nonNilEquals(.Points[0], ) || nonNilEquals(.Points[len(.Points)-1], ) {
			return true
		}
	}
	return false
}

/*
The edge to the left may have routed first and been more optimal
The edge to the right then routed, but could not route optimally due to obstruction
So we balance by going to the less optimal spot, since branching from same point is still more aesthetically pleasing
// ┌──────────┐                ┌───────────┐
// │          │                │           │
// │          │                │           │
// └──────────┘                └───────────┘
//      ▲                            ▲
//      │                            │
//      │                            │
//      │              ┌─────────────┘
//      │              │
//      │              │
//      │              │
//      │              │
//      └──────────────┤
//                     │
//                     │
//                     │
//              ┌──────┴──────┐
//              │             │
//              │             │
//              │             │
//              │             │
//              └─────────────┘
*/