from Code.Communication.APIRequests import APIRequests
from Code.Communication.Direction import Direction, mirror
from Code.Communication.Member import Member
from Code.Config import GeneralConfig


class Neighbours:

	def __init__(self, own_process: Member):
		self.neighbours = {}
		self.own_process = own_process
		self.api = APIRequests()

	def connect(self, direction, ip, port) -> int:
		print(f"connecting to {ip}:{port} on  {direction} side")
		new_neighbour,counter = self.api.connectToMember(self.own_process, ip, port, mirror(direction))
		self.neighbours[direction] = new_neighbour
		return counter

	def accept_connection(self, direction: Direction, ip, port) -> tuple[Member, bool]:
		if direction in self.neighbours:
			return self.neighbours[direction], False

		member = Member(ip, port)
		print(f"Adding neighbour {member.__repr__()}")
		self.neighbours[direction] = member
		return self.own_process, True

	def get_edge(self, direction: Direction,counter:int):
		if direction in self.neighbours:
			return self.api.get_edge(self.neighbours[direction], mirror(direction),counter)
		elif direction == Direction.RIGHT or direction.LEFT:
			return [False] * GeneralConfig.fields_amount_y


	def toggle_pause(self,new_state:bool):
		for neighbour in self.neighbours.values():
			print(f"Telling member {neighbour} toggle pause with {new_state}")
			self.api.toggle_pause(neighbour,new_state)
