import grpc
from common.database.api.Database import Database
from common.database.api.context.topology.link.Link import Link
from common.exceptions.ServiceException import ServiceException

def check_link_exists(database : Database, context_id : str, topology_id : str, link_id : str) -> Link:
    db_context = database.context(context_id).create()
    db_topology = db_context.topology(topology_id).create()
    if db_topology.links.contains(link_id): return db_topology.link(link_id)
    msg = 'Context({})/Topology({})/Link({}) does not exist in the database.'
    msg = msg.format(context_id, topology_id, link_id)
    raise ServiceException(grpc.StatusCode.NOT_FOUND, msg)

def check_link_not_exists(database : Database, context_id : str, topology_id : str, link_id : str):
    db_context = database.context(context_id).create()
    db_topology = db_context.topology(topology_id).create()
    if not db_topology.links.contains(link_id): return
    msg = 'Context({})/Topology({})/Link({}) already exists in the database.'
    msg = msg.format(context_id, topology_id, link_id)
    raise ServiceException(grpc.StatusCode.ALREADY_EXISTS, msg)
