1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
#[macro_use] extern crate log;
use std::collections::HashMap as Map;
use std::collections::BTreeSet as Set;
use tui::layout::Margin;
use tui::style::Color;
use tui::style::Modifier;
use tui::{
	layout::Rect,
	buffer::Buffer,
	style::Style,
	widgets::{Block, Widget, BorderType, Borders},
};

pub struct NodeLayout<'a> {
	// minimum size of contents (TODO: doc: including borders?)
	size: (u16, u16),
	border: BorderType,
	title: &'a str,
//	in_ports: Vec<PortLayout>,
//	out_ports: Vec<PortLayout>,
}

impl<'a> NodeLayout<'a> {
	pub fn new(size: (u16, u16)) -> Self {
		Self {
			size,
			border: BorderType::Rounded,
			title: "",
		}
	}

	pub fn with_title(mut self, title: &'a str) -> Self {
		self.title = title;
		self
	}
}

/*
pub struct PortLayout {
}
*/

#[derive(Default)]
pub struct NodeGraph<'a> {
	nodes: Vec<NodeLayout<'a>>,
	connections: Vec<Connection>,
	placements: Map<usize, Rect>,
	conn_layout: Map<Connection, ConnectionLayout>,
	alias_connections: Map<(bool, usize, usize), &'static str>,
}

impl<'a> NodeGraph<'a> {
	pub fn new(
		nodes: Vec<NodeLayout<'a>>,
		connections: Vec<Connection>,
	) -> Self {
		Self {
			nodes,
			connections,
			..Self::default()
		}
	}

	pub fn calculate(&mut self) {
		self.placements.clear();

		// find root nodes
		let mut roots: Set<_> = (0..self.nodes.len()).collect();
		for ea_connection in self.connections.iter() {
			roots.remove(&ea_connection.from_node);
		}

		// place them and their children (recursively)
		let mut main_chain = Vec::new();
		for ea_root in roots {
			self.place_node(ea_root, 0, 0, &mut main_chain);
			assert!(main_chain.is_empty());
		}

		// calculate connections (eventually, this should be done during node
		// placement, but thats really complicated and i dont wanna deal with that
		// right now. essentially, adding non-trivial connections nudges nodes,
		// and nudging nodes nudges existing connections.)
		self.connections.sort_by(|a,b| {
			match a.from_node.cmp(&b.from_node) {
				std::cmp::Ordering::Equal => a.from_port.cmp(&b.from_node),
				other => other,
			}
		});
		let mut idx_alias = 0;
		'conn: for ea_conn in self.connections.iter().copied() {
			let a_pos = self.placements[&ea_conn.from_node];
			let b_pos = self.placements[&ea_conn.to_node];
			// NOTE: don't forget that left and right are swapped
			let a_point = (a_pos.left(), a_pos.top() + ea_conn.from_port as u16 + 1);
			let b_point = (b_pos.right() + 1, b_pos.top() + ea_conn.to_port as u16 + 1);
			// check for intersections
			{
				let conn_bbox = Rect {
					x: a_point.0.min(b_point.0),
					y: a_point.1.min(b_point.1),
					width: a_point.0.abs_diff(b_point.0),
					height: a_point.1.abs_diff(b_point.1),
				};
				for ea_node in self.placements.values() {
					if conn_bbox.intersects(*ea_node) {
						let from = (false, ea_conn.from_node, ea_conn.from_port);
						let to = (true, ea_conn.to_node, ea_conn.to_port);
						if let Some(alias) = self.alias_connections.get(&from) {
							self.alias_connections.insert(to, *alias);
						}
						else {
							let alias = ALIAS_CHARS[idx_alias];
							idx_alias += 1;
							self.alias_connections.insert(from, alias);
							self.alias_connections.insert(to, alias);
						}
						continue 'conn
					}
				}
			};
			let layout = self.conn_layout.entry(ea_conn)
				.or_insert(ConnectionLayout::new(a_point));
			if a_point.0 < b_point.0 {
				debug!("skipped due to reversed direction {ea_conn:?}");
				continue
			}
			if a_point.1 != b_point.1 { // different heights
				let midpoint = (a_point.0 + b_point.0)/2;
				if midpoint != a_point.0 {
					// right
					layout.points.push((Direction::East, a_point.0 - midpoint));
				}
				// up/down
				if a_point.1 > b_point.1 {
					layout.points.push((Direction::North, a_point.1 - b_point.1));
				}
				else {
					layout.points.push((Direction::South, b_point.1 - a_point.1));
				}
				if midpoint != b_point.0 {
					// right
					layout.points.push((Direction::East, midpoint - b_point.0));
				}
			}
			else if a_point.0 != b_point.0 {
				layout.points.push((Direction::East, a_point.0 - b_point.0));
			}
			// `layout.points` should be empty if `a_point` and `b_point` are the same
		}
	}

	/// ATTENTION: x_offs works in the opposite direction (higher values are
	/// further left) and y_offs is the same as tui (higher values are further
	/// down)
	fn place_node(&mut self, idx_node: usize, x: u16, y: u16, main_chain: &mut Vec<usize>) {
		// place the node
		let size_me = self.nodes[idx_node].size;
		let mut rect_me = Rect { x, y, width: size_me.0, height: size_me.1 };

		// nudge placement. if a node intersects with another node, its entire
		// main chain (largest subset of nodes including this one where every
		// node is the first child of its parent) should be moved down to not
		// intersect.
		let mut bottom = y;
		for (_, ea_them) in self.placements.iter() {
			if rect_me.intersects(*ea_them) {
				bottom = bottom.max(ea_them.bottom());
			}
		}
		for ea_node in main_chain.iter() {
			let y = self.placements[ea_node].y.max(bottom);
			self.placements.get_mut(ea_node).unwrap().y = y;
		}
		rect_me.y = bottom;
		self.placements.insert(idx_node, rect_me);

		// find children and order them
		let mut y = y;
		main_chain.push(idx_node);
		for ea_child in get_upstream(&self.connections, idx_node) {
			if self.placements.contains_key(&ea_child.from_node) {
				// nudge it (if necessary)
				self.nudge(ea_child.from_node, rect_me.x + rect_me.width + 3);
			}
			else {
				// place it
				self.place_node(ea_child.from_node, x + rect_me.width + 3, y, main_chain);
				main_chain.clear();
				y += self.placements[&ea_child.from_node].height;
			}
		}
		main_chain.pop();
	}

	fn nudge(&mut self, idx_node: usize, x: u16) {
		let rect_me = self.placements[&idx_node];
		if rect_me.x < x {
			self.placements.get_mut(&idx_node).unwrap().x = x;
			for ea_child in get_upstream(&self.connections, idx_node) {
				assert!(self.placements.contains_key(&ea_child.from_node));
				self.nudge(ea_child.from_node, x + rect_me.width + 3);
			}
		}
	}

	pub fn split(&self, area: Rect) -> Vec<Rect> {
		(0..self.nodes.len()).map(|idx_node| {
			self.placements.get(&idx_node).map(|pos| {
				if pos.right() > area.width || pos.bottom() > area.height {
					return Rect { x: 0, y: 0, width: 0, height: 0, }
				}
				let mut pos = *pos;
				pos.x = area.width - pos.right();
				pos.inner(&Margin { horizontal: 1, vertical: 1 })
			})
			.unwrap_or_default()
		}).collect()
	}
}

fn get_upstream(conns: &Vec<Connection>, idx_node: usize) -> Vec<Connection> {
	// find children and order them
	let mut upstream: Vec<_> = conns.iter()
		.filter(|ea| { ea.to_node == idx_node })
		.copied()
		.collect();
	upstream.sort_by(|a,b| a.to_port.cmp(&b.to_port));
	upstream
}

fn get_downstream(conns: &Vec<Connection>, idx_node: usize) -> Vec<Connection> {
	// find parents and order them
	let mut downstream: Vec<_> = conns.iter()
		.filter(|ea| { ea.from_node == idx_node })
		.copied()
		.collect()
	;
	downstream.sort_by(|a,b| a.from_port.cmp(&b.from_port));
	downstream
}


/*
pub struct NodeGraphState {
	x_offset: usize,
	y_offset: usize,
}
*/

#[derive(Debug, Clone)]
pub struct ConnectionLayout {
	start_pos: (u16, u16),
	points: Vec<(Direction, u16)>,
	border: BorderType,
	style: Style,
}

impl ConnectionLayout {
	fn new(start_pos: (u16, u16)) -> Self {
		Self {
			start_pos,
			points: Vec::new(),
			border: BorderType::Double,
			style: Style::default(),
		}
	}
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
enum Direction {
	North,
	South,
	East,
	#[allow(unused)]
	West,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Connection {
	pub from_node: usize,
	pub from_port: usize,
	pub to_node: usize,
	pub to_port: usize,
}

impl Connection {
	pub fn new(from_node: usize, from_port: usize, to_node: usize, to_port: usize) -> Self {
		Self { from_node, from_port, to_node, to_port, }
	}
}

impl<'a> tui::widgets::StatefulWidget for NodeGraph<'a> {
	// eventually, this will contain stuff like view position
//	type State = NodeGraphState;
	type State = ();

	fn render(self, area: Rect, buf: &mut Buffer, _state: &mut Self::State) {
		assert!(self.alias_connections.len() == 2);
		// draw connections
		'conn: for ea_layout in self.conn_layout.values() {
			let symbols = BorderType::line_symbols(ea_layout.border);
			let mut current_position = ea_layout.start_pos;
			let mut last_dir = Direction::East;
			use Direction::*;
			for (ea_direction, ea_distance) in ea_layout.points.iter() {
				let corner = match (ea_direction, last_dir) {
					(East,  East ) | (West,  West ) => symbols.horizontal,
					(East,  West ) | (West,  East ) => unreachable!(),
					(North, North) | (South, South) => symbols.vertical,
					(North, South) | (South, North) => unreachable!(),
					(East,  North) | (South, West ) => symbols.top_left,
					(West,  North) | (South, East ) => symbols.top_right,
					(East,  South) | (North, West ) => symbols.bottom_left,
					(West,  South) | (North, East ) => symbols.bottom_right,
				};
				if current_position.0 > area.width || current_position.1 >= area.bottom() { continue 'conn }
				buf.get_mut(area.width - current_position.0, current_position.1)
					.set_symbol(corner)
					.set_style(ea_layout.style);
				match ea_direction {
					Direction::East => {
						for idx in 1..*ea_distance {
							if current_position.0 - idx > area.width || current_position.1 >= area.bottom() { continue 'conn }
							buf.get_mut(area.width - (current_position.0 - idx), current_position.1)
								.set_symbol(symbols.horizontal)
								.set_style(ea_layout.style);
						}
						current_position.0 -= ea_distance;
					}
					Direction::West => {
						for idx in 1..*ea_distance {
							if current_position.0 + idx > area.width || current_position.1 >= area.bottom() { continue 'conn }
							buf.get_mut(area.width - (current_position.0 + idx), current_position.1)
								.set_symbol(symbols.horizontal)
								.set_style(ea_layout.style);
						}
						current_position.0 += ea_distance;
					}
					Direction::North => {
						for idx in 1..*ea_distance {
							if current_position.0 > area.width || current_position.1 - idx >= area.bottom() { continue 'conn }
							buf.get_mut(area.width - current_position.0, current_position.1 - idx)
								.set_symbol(symbols.vertical)
								.set_style(ea_layout.style);
						}
						current_position.1 -= ea_distance;
					}
					Direction::South => {
						for idx in 1..*ea_distance {
							if current_position.0 > area.width || current_position.1 + idx >= area.bottom() { continue 'conn }
							buf.get_mut(area.width - current_position.0, current_position.1 + idx)
								.set_symbol(symbols.vertical)
								.set_style(ea_layout.style);
						}
		            current_position.1 += ea_distance;
					}
				}
				last_dir = *ea_direction;
			}
			if current_position.0 > area.width || current_position.1 >= area.bottom() { continue 'conn }
			let corner = match last_dir {
				East  => symbols.horizontal,
				West  => unreachable!(),
				North => symbols.top_left,
				South => symbols.bottom_left,
			};
			buf.get_mut(area.width - current_position.0, current_position.1)
				.set_symbol(corner)
				.set_style(ea_layout.style);
		}

		// draw nodes
		'node: for (idx_node, ea_node) in self.nodes.into_iter().enumerate() {
			if let Some(mut pos) = self.placements.get(&idx_node).copied() {
				if pos.right() > area.width || pos.bottom() > area.height { continue 'node }
				// draw box
				pos.x = area.width - pos.right();
				let block = Block::default().border_type(ea_node.border).borders(Borders::ALL).title(ea_node.title);
				block.render(pos, buf);
				// draw connection ports
				for ea_conn in get_upstream(&self.connections, idx_node) {
					// draw connection alias
					if let Some(alias_char) = self.alias_connections.get(&(true, idx_node, ea_conn.to_port)) {
						buf.get_mut(pos.left() - 1, pos.top() + ea_conn.to_port as u16 + 1)
							.set_symbol(alias_char)
							.set_style(Style::default().add_modifier(Modifier::BOLD).bg(Color::Red))
						;
					}

					// draw port
					buf.get_mut(pos.left(), pos.top() + ea_conn.to_port as u16 + 1)
						.set_symbol(conn_symbol(true, ea_node.border, BorderType::Double))
					;
				}
				for ea_conn in get_downstream(&self.connections, idx_node) {
					// draw connection alias
					if let Some(alias_char) = self.alias_connections.get(&(false, idx_node, ea_conn.from_port)) {
						buf.get_mut(pos.right(), pos.top() + ea_conn.from_port as u16 + 1)
							.set_symbol(alias_char)
							.set_style(Style::default().add_modifier(Modifier::BOLD).bg(Color::Red))
						;
					}

					// draw port
					buf.get_mut(pos.right() - 1, pos.top() + ea_conn.from_port as u16 + 1)
						.set_symbol(conn_symbol(false, ea_node.border, BorderType::Double))
					;
				}
			}
			else {
				buf.set_string(0, idx_node as u16, format!("{idx_node}"), Style::default());
			}
		}
	}
}

fn conn_symbol(is_input: bool, block_style: BorderType, conn_style: BorderType) -> &'static str {
	let out = match (block_style, conn_style) {
		(BorderType::Plain
		|BorderType::Rounded, BorderType::Thick)   => ("┥", "┝"),
		(BorderType::Plain
		|BorderType::Rounded, BorderType::Double)  => ("╡", "╞"),
		(BorderType::Plain
		|BorderType::Rounded, BorderType::Plain
		                    | BorderType::Rounded) => ("┤", "├"),

		(BorderType::Thick,   BorderType::Thick)   => ("┫", "┣"),
		(BorderType::Thick,   BorderType::Double)  => ("X", "X"),
		(BorderType::Thick,   BorderType::Plain
		                    | BorderType::Rounded) => ("┨", "┠"),

		(BorderType::Double,  BorderType::Thick)   => ("X", "X"),
		(BorderType::Double,  BorderType::Double)  => ("╣", "╠"),
		(BorderType::Double,  BorderType::Plain
		                    | BorderType::Rounded) => ("╢", "╟"),
	};
	if is_input { out.0 } else { out.1 }
}

const ALIAS_CHARS: [&str; 24] = [
	"α", "β", "γ", "δ", "ε", "ζ", "η", "θ", "ι", "κ", "λ", "μ", "ν", "ξ", "ο", "π", "ρ", "σ", "τ", "υ", "φ", "χ", "ψ", "ω",
];