import json, datetime, re
from flask import Flask, request, g, Response, jsonify
from functools import wraps
import accounts

def auth(route_function):
  @wraps(route_function)
  def decorated_function(*args, **kwargs):
    if 'Authorization' not in request.headers:
      return jsonify({'success': False, 'message': 'This resource requires authentication'}), 401
    g.user = accounts.get_user_context(request, request.headers['Authorization'].replace('Bearer ', ''))
    if g.user is None:
      return jsonify({'success': False, 'message': 'Invalid authorisation token'}), 401
    return route_function(*args, **kwargs)
  return decorated_function

def maybe_auth(route_function):
  @wraps(route_function)
  def decorated_function(*args, **kwargs):
    if 'Authorization' in request.headers:
      g.user = accounts.get_user_context(request, request.headers['Authorization'].replace('Bearer ', ''))
    else: g.user = None
    return route_function(*args, **kwargs)
  return decorated_function

class JsonEncoder(json.JSONEncoder):
 def default(self, obj):
   if isinstance(obj, (datetime.datetime, datetime.date)):
     return obj.isoformat() 
   elif isinstance(obj, ObjectId):
     return str(obj)
     return json.JSONEncoder.default(self, obj) 

def jsonify(*args, **kwargs):
 return json.dumps(dict(*args, **kwargs), cls=JsonEncoder)
