from flask import render_template, Blueprint, request, flash, jsonify
from flask_login import login_required, current_user
from .models import Note
from . import db
import json


views = Blueprint('views', __name__)

@views.route('/home', methods=['GET', 'POST'])
@login_required
def home():
	if request.method == 'POST':
		content = request.form.get('content')
		if len(content) < 1:
			flash('Content too short', category='error')
		else:
			new_note = Note(user_id=current_user.id, content=content)
			db.session.add(new_note)
			db.session.commit()
			flash('Note added!', category='success')

	return render_template('home.html', user=current_user)


@views.route('/', methods=['GET', 'POST'])
def main():
	return render_template('index.html', title='Thor Note')

@views.route('/delete-note', methods=['POST'])
def delete_note():
	note = json.loads(request.data)
	note_id = note['note_id']
	note = Note.query.get(note_id)
	if note:
		if note.user_id == current_user.id:
			db.session.delete(note)
			db.session.commit()
			flash('note deleted', category='success')

	return jsonify({})