from flask import Flask, jsonify, request, g
from util import util
import files, accounts, passwords

app = Flask(__name__)

@app.errorhandler(404)
def handle_404(e):
  return jsonify({'message': 'Resource not found'}), 404

@app.errorhandler(429)
def handle_429(e):
  return jsonify({'message': 'Rate limit exceeded', 'Allowed limit': e.description}), 429

@app.errorhandler(500)
def handle_500():
  return jsonify({'message': 'There was a problem with this request. Please try again later.'}), 500

@app.route('/accounts', methods=['POST'])
def accounts_route():
  if request.method == 'POST':
    return accounts.create(request.get_json())

@app.route('/accounts/password/tokens', methods=['POST', 'PUT'])
def password_tokens_route():
  if request.method == 'POST':
    return passwords.create_reset_token()
  if request.method == 'PUT':
    return passwords.update(request.get_json())

@app.route('/tokens', methods=['POST'])
def tokens_post_route():
  if request.method == 'POST':
    return accounts.login(request.get_json())

@app.route('/tokens', methods=['DELETE'])
@util.auth
def tokens_delete_route():
  if request.method == 'DELETE':
    return accounts.logout(g.user)

@app.route('/tokens/all', methods=['DELETE'])
@util.auth
def tokens_all_delete_route():
  if request.method == 'DELETE':
    return accounts.logout_all(g.user)

@app.route('/files', methods=['POST', 'GET'])
@util.auth
def files_route():
  if request.method == 'POST':
    return files.create(g.user)
  if request.method == 'GET':
    return files.get(g.user)

@app.route('/files/<key>', methods=['PUT', 'GET', 'DELETE'])
@util.auth
def file_route(key):
  if request.method == 'PUT':
    return files.update_file(g.user, key)
  if request.method == 'GET':
    return files.get_file(g.user, key)
  if request.method == 'DELETE':
    return files.delete_file(g.user, key)
