from datetime import timedelta

from django.conf import settings
from django.utils import timezone

from authentications.decorators import ep_authenticated_user
from .api import get_ep_client


@ep_authenticated_user
def __get_ep_sessionid(request):
    epc, group = get_ep_client()
    if not epc or not group:
        return None, None

    author = epc.createAuthorIfNotExistsFor(
        name=str(request.user), authorMapper=str(request.user)
    )
    expires = timezone.now() + timedelta(hours=3)
    
    try:
        result = epc.createSession(
            groupID=str(group["groupID"]),
            authorID=str(author["authorID"]),
            validUntil=str(int(expires.timestamp())),
        )
    except Exception as e:
        raise e

    return result["sessionID"], expires


def add_ep_cookie(request, response):
    ep_sessid, expires = __get_ep_sessionid(request)

    if ep_sessid:
        response.set_cookie(
            "sessionID", ep_sessid, expires=expires, domain=settings.HOST_NAME, path="/"
        )
        response.set_cookie("sessionID", ep_sessid, expires=expires, path="/etherpad")
    return response


def del_ep_cookie(request, response):
    if "sessionID" in request.COOKIES:
        ep_sessionID = request.COOKIES["sessionID"]

        epc, group = get_ep_client()
        epc.deleteSession(sessionID=ep_sessionID)

        response.delete_cookie("sessionID", domain=settings.HOST_NAME, path="/")
    return response
