import os, datetime
from flask import request, jsonify, Response
from util import database

max_size = 512 * 1024

def create(user):
  default_path = request.headers.get('Default-Path')
  key = request.headers.get('Key')  
  db = database.get_db()
  existing = db.configs.find_one({'key': key, 'user': user['_id']})
  if existing:
    return jsonify({'success': False, 'message': 'A key with this name already exists'}), 400
  data = request.get_data()
  if len(data) > max_size:
    return jsonify({'success': False, 'message': 'File is too large'}), 400
  if not key or not default_path or not data:
    return jsonify({'success': False, 'message': 'Invalid request'}), 400
  now = datetime.datetime.utcnow()
  db.configs.insert_one({'key': key, 'defaultPath': default_path, 'createdAt': now, 'updatedAt': now, 'object': data, 'user': str(user['_id'])})
  return jsonify({'success': True}), 200

def get(user):
  db = database.get_db()
  files_list = list(db.configs.find({'user': user['_id']}, {'_id': 0, 'key': 1, 'defaultPath': 1}))
  return jsonify(files_list), 200

def update_file(user, key):
  db = database.get_db()
  existing = db.configs.find_one({'key': key, 'user': str(user['_id'])})
  if not existing:
    return jsonify({'success': False, 'message': 'A file with this key could not be found'}), 404
  data = request.get_data()
  if len(data) > max_size:
    return jsonify({'success': False, 'message': 'File is too large'}), 400
  if not key or not data:
    return jsonify({'success': False, 'message': 'Invalid request'}), 400
  now = datetime.datetime.utcnow()
  db.configs.update_one({'_id': existing['_id']}, {'$set': {'updatedAt': now, 'object': data}})
  return jsonify({'success': True}), 200

def get_file(user, key):
  db = database.get_db()
  existing = db.configs.find_one({'key': key, 'user': str(user['_id'])})
  if not existing:
    return jsonify({'success': False, 'message': 'The specified file could not be found'}), 404
  resp = Response(existing['object'])
  resp.headers['Default-Path'] = existing['defaultPath']
  return resp

def delete_file(user, key):
  db = database.get_db()
  existing = db.configs.find_one({'key': key, 'user': str(user['_id'])})
  if not existing:
    return jsonify({'success': False, 'message': 'The specified file could not be found'}), 404
  db.configs.remove({'key': key, 'user': user['_id']})
  return jsonify({'success': True}), 200
