import json

EVENT_COMPLETED = "__omnis__internal__completed__"
EVENT_ERROR = "__omnis__internal__error__"

async def sendEvent(data, response, eventName="message"):
    if response._closed:
        return
    payload = json.dumps({"payload": data})
    msg = f"event: {eventName}\ndata: {payload}\n\n"
    await response.send(msg)

async def sendResponse(data, response):
    await sendEvent(data, response, eventName=EVENT_COMPLETED)
    await response.close()

async def sendError(errorText, response, errorCode=400):
    data = {
        "errorInfo": errorText,
        "errorCode": errorCode
    }
    await sendEvent(data, response, eventName=EVENT_ERROR)
    await response.close()
