import json
from random import choice
from string import ascii_letters, digits

from app import cache

ENCODING = "utf-8"


def new_code(email, purpose):
    code = "".join(choice(ascii_letters+digits) for x in range(5)).upper()
    return set_code(email, code, purpose)


def set_code(email, code, purpose):
    data = json.dumps({"code": code, "purpose": purpose})
    cache.set(email, bytes(data, encoding=ENCODING), timeout=60*60*24)
    return code


def verify_code(email, code):
    code = code.upper()
    cached_data = cache.get(email)
    if not cached_data:
        raise WrongCodeError
    cached_data = json.loads(str(cached_data, encoding=ENCODING))
    if cached_data["code"] != code:
        raise WrongCodeError
    cache.delete(email)
    return cached_data["purpose"]


class WrongCodeError(Exception):
    pass
