from flask import Flask, render_template, request
import os
import json
import mistletoe

app = Flask(__name__,static_folder='static')
contents = []
folder = "./static/assets/"

f = open('db.json',)
data = json.load(f,)
print(data)

D = {}
L = []

def list_files(startpath):
    for root, dirs, files in os.walk(startpath):
        root_dir = os.path.basename(root)
        for f in files:
            L.append([root_dir,f])

    for i in range(len(L)):
        # If the key is already 
        # present in dictionary
        # then append the value 
        # to the list of values
        if L[i][0] in D:
            if L[i][1].startswith("."):
                print('nope')
            else:
                if L[i][1].endswith("txt"):
                    print(L[i][0])
                    file_path = f"{folder}{L[i][0]}/{L[i][1]}"
                    with open(file_path) as txt:
                        output = txt.read()
                        D[L[i][0]].append(output)
                elif L[i][1].endswith("md"):

                    file_path = f"{folder}{L[i][0]}/{L[i][1]}"
                    print(file_path)
                    with open(file_path, 'r') as md:

                        output = mistletoe.markdown(md)
                        D[L[i][0]].append(output)        
                else:
                    D[L[i][0]].append(L[i][1])
        # If the key is not present
        # in the dictionary then add
        # the key-value pair
        else:
            D[L[i][0]]= []
            if L[i][1].startswith("."):
                print('nope')
            else:
                if L[i][1].endswith("txt"):
                    print(L[i][1])
                    file_path = f"{folder}{L[i][0]}/{L[i][1]}"
                    with open(file_path) as txt:
                        output = txt.read()
                        D[L[i][0]].append(output)
                elif L[i][1].endswith("md"):

                    file_path = f"{folder}{L[i][0]}/{L[i][1]}"
                    print(file_path)
                    with open(file_path, 'r') as md:

                        output = mistletoe.markdown(md)
                        D[L[i][0]].append(output)
                else:
                    D[L[i][0]].append(L[i][1])

    with open("db.json", "w") as outfile: 
        json.dump(D, outfile) 

list_files(folder)

@app.route("/", methods=['GET', 'POST'])
def platform():

    if request.form.getlist('test') == '0':
    # do something
        print(request.form.getlist('test'))

    # inputt = request.form['test']
    # print(inputt)        
    
    return render_template("index.html", data = data, folder = folder )
