from dataclasses import asdict

import requests as requests

from Code.Communication.Direction import Direction
from Code.Communication.Member import Member


class APIRequests:

	def connectToMember(self, own_process: Member, ip, port, direction: Direction) -> (Member,int):
		body = asdict(own_process)
		response = requests.post(f"http://{ip}:{port}/connect/{direction.name}", json=body,allow_redirects=True)
		jsonValue = response.json()
		return Member(jsonValue["ip"], jsonValue["port"]),int(jsonValue["counter"])

	def get_edge(self, target: Member, direction: Direction,counter:int):
		print(f"Getting {direction} edge from {target} with url http://{target.ip}:{target.port}/border/{direction.name}")
		response = requests.get(f"http://{target.ip}:{target.port}/border/{direction.name}?counter={counter}")
		print(f"Got {direction} edge from {target}")
		return response.json()

	def toggle_pause(self, neighbour: Member, new_state: bool):
		action = "start" if new_state else "stop"
		print(f"sending {action} to {neighbour}")
		response = requests.post(f"http://{neighbour.ip}:{neighbour.port}/pause/{action}")
