import flask
from flask import render_template, jsonify, request, redirect
import json
import os
import markdown

app = flask.Flask(__name__)

@app.route('/')
def home():
    return render_template('index.html')

@app.route('/read')
def readBook():
    filepath = request.args.get('filepath')+"/book.md"
    with open(filepath) as f:
        mdtext = f.read()
    notespath = request.args.get('filepath')+"/notes.txt"
    with open(notespath) as f:
        notestext = f.read()
    renderedMd = markdown.markdown(mdtext)
    return render_template('read.html', markdown=renderedMd, path=request.args.get('filepath'), notes=notestext)

@app.route('/notes')
def notesForBook():
    notespath = request.args.get('filepath')+"/notes.txt"
    with open(notespath) as f:
        notestext = f.read()
    return render_template('notes.html', path=notespath, notes=notestext)

@app.route('/savenotes', methods=['POST'])
def saveNotes():
    path = request.form.get("path")+"/notes.txt"
    notes = request.form.get("notes")
    with open(path, "w") as f:
        f.write(notes)
    return redirect("http://localhost:5000/", code=302)

@app.route('/api/textbooks')
def textbooks():
    textbook_list = []
    
    dir = './textbooks' 

    for dirpath, dirnames, filenames in os.walk(dir):
        if 'manifest.json' in filenames:
            manifest_path = os.path.join(dirpath, 'manifest.json')
            try:
                with open(manifest_path, 'r', encoding='utf-8') as f:
                    manifest_data = json.load(f) 
                data = {
                    "path": dirpath,
                    "name": manifest_data.get("name"),
                    "author": manifest_data.get("author")
                }
                textbook_list.append(data)
                print(json.dumps(data, indent=2))
            except:
                pass
                
    return jsonify(textbook_list)

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