#!/usr/bin/env python3
from flask import Flask, jsonify, request
from json import dumps, loads
from pathlib import Path
from secrets import token_urlsafe
from werkzeug.utils import secure_filename

app = Flask(__name__)
app.secret_key = token_urlsafe(32)

@app.route('/<note>', methods=['GET'])
def get(note: str):
    path = Path(secure_filename(note))

    try:
        raw_data = path.read_text()
    except:
        return jsonify({'success': False, 'error': f'no such note: {note}'})

    try:
        data = loads(raw_data)
    except:
        return jsonify({'success': False, 'error': f'malformed note json: {raw_data}'})

    title = data.get('title')
    content = data.get('content')
    if not title or not content:
        return jsonify({'success': False, 'error': f'malformed note json: {raw_data}'})

    return jsonify({'success': True, 'note': {'title': title, 'content': content}})

@app.route('/<note>', methods=['POST'])
def set(note: str):
    body = request.get_json(silent=True)
    if body is None:
        return jsonify({'success': False, 'error': 'bad json'})

    title = body.get('title')
    content = body.get('content')

    if title is None or content is None:
        return jsonify({'success': False, 'error': f'bad request: {body!r}'})

    path = Path(secure_filename(note))
    try:
        path.write_text(dumps({'title': title, 'content': content}))
    except:
        return jsonify({'success': False, 'error': f'failed to store note'})

    return jsonify({'success': True})

if __name__ == '__main__':
    app.run()
