from django.http import JsonResponse
import jwt
from jwt.exceptions import ExpiredSignatureError, InvalidSignatureError

def successRes(msg):
    return JsonResponse({'status':200, 'data': msg})


def errorRes(msg="", default=False, status=400):
    if default:
        return JsonResponse({'status':status, 'msg': 'Server error'})
    else:
        return JsonResponse({'status':status, 'msg': msg})


def validateData(data, req):
    values = [None]*len(data)
    for i in range(len(data)):
        var = req.data.get(data[i])
        if var:
            if type(var) is not int and type(var) is not list:
                values[i]= f"'{req.data.get(data[i])}'"
            else:
                values[i]= req.data.get(data[i])
        else:
                values[i] = "NULL"
    return values

class TokenError(Exception):
    pass


def verify(token, superadmin=False):
    try:
        if not token:
            raise Exception("No token provided")
        tokenIsValid = jwt.decode(token, 'ibiye4700', algorithms=["HS256"], options={"verify_signature": True, "require": ["exp"]})
        if(superadmin):
            if(tokenIsValid["is_superuser"]):
                return tokenIsValid
            else:
                return Exception("You don't have access to this resource")
        else:
            return tokenIsValid
    except ExpiredSignatureError:
        raise TokenError("Login token has expired. Please login again.")
    except InvalidSignatureError:
        raise TokenError("token is invalid")
    except Exception as err:
        raise TokenError(str(err))