import json
from .utils import generate_random_id

class Node:
	def __init__(self, data):
		self.id = data['id']
		self.type = data['type']

		self.x = data['x']
		self.y = data['y']
		self.height = data['height']
		self.width = data['width']
		
		self.styleAttributes = data['styleAttributes']

		self.label = data.get('label', '')
		self.text = data.get('text', '')
	
	def toJSON(self):
		retval = {
			'id': self.id,
			'label': self.label,
			'type': self.type,
			'x': self.x,
			'y': self.y,
			'height': self.height,
			'width': self.width,
			'styleAttributes': self.styleAttributes
		}

		if self.text:
			retval['text'] = self.text
		
		return retval

class Edge:
	def __init__(self, data):
		self.id = data['id']
		self.fromNode = data['fromNode']
		self.toNode = data['toNode']
		self.fromSide = data['fromSide']
		self.toSide = data['toSide']
		self.styleAttributes = data['styleAttributes']
	
	def toJSON(self):
		return {
			'id': self.id,
			'fromNode': self.fromNode,
			'toNode': self.toNode,
			'fromSide': self.fromSide,
			'toSide': self.toSide,
			'styleAttributes': self.styleAttributes
		}

class ObsidianCanvas:
	def __init__(self, data):
		self.nodes = []
		self.edges = []

		if 'nodes' in data:
			for node in data['nodes']:
				self.nodes.append(Node(node))
		if 'edges' in data:
			for edge in data['edges']:
				self.edges.append(Edge(edge))

	def add_node(self, node):
		self.nodes.append(node)

	def connect(self, fromNode, toNode, fromSide='bottom', toSide='top'):
		edge = Edge({
			'id': generate_random_id(),
			'fromNode': fromNode.id,
			'toNode': toNode.id,
			'fromSide': fromSide,
			'toSide': toSide,
			'styleAttributes': {}
		})
		self.edges.append(edge)
		return edge

	def save(self, filename):
		with open(filename, 'w') as f:
			json.dump({
				'nodes': [node.toJSON() for node in self.nodes],
				'edges': [edge.toJSON() for edge in self.edges]
			}, f, indent=2)