import flask
import urllib, json
import os
from update import *

# To add: server feedback (logging + capacity) using socket io in Flask
# https://towardsdatascience.com/how-to-add-on-screen-logging-to-your-flask-application-and-deploy-it-on-aws-elastic-beanstalk-aa55907730f

# Create the application.
APP = flask.Flask(__name__)

# ---

PROJECT_NAME = 'volumetric-regimes'
DIR_PATH = '.' # without trailing slash
PORTNUMBER = 5522
WIKI = 'https://possiblebodies.constantvzw.org/book' # remove tail slash '/'
PAGENAME = 'Unfolded'
STYLESHEET = f'{ PROJECT_NAME }.css'

# ---


def download(STYLESHEET):
	# using etherpump
	os.system(f'{ DIR_PATH }/venv/bin/etherpump gettext { STYLESHEET } > { DIR_PATH }/static/css/{ STYLESHEET }')

@APP.route('/', methods=['GET'])
def pad():
	if not os.path.exists(f'{ DIR_PATH }/static/Unfolded.html'):
		download(STYLESHEET) # download the stylesheet pad
		publication_unfolded = update_material_now(PAGENAME, WIKI) # download the latest version of the page
		with open(f'{ DIR_PATH }/static/Unfolded.html', 'w') as out:
			out.write(publication_unfolded) # save the html (without <head>) to file
	else:
		publication_unfolded = open(f'{ DIR_PATH }/static/Unfolded.html', 'r').read()

	return flask.render_template('flask/index.html', title=PROJECT_NAME)

@APP.route('/notes/', methods=['GET'])
def notes():
        return flask.render_template('flask/notes.html')

@APP.route('/update/', methods=['GET', 'POST'])
def update():
	publication_unfolded = update_material_now(PAGENAME, WIKI) # download the latest version of the page
	with open(f'{ DIR_PATH }/static/Unfolded.html', 'w') as out:
		out.write(publication_unfolded) # save the html (without <head>) to file

	return flask.render_template('flask/index.html', title=PROJECT_NAME)

@APP.route('/pagedjs/', methods=['GET', 'POST'])
def pagedjs():
	download(STYLESHEET) # download the stylesheet pad
	publication_unfolded = open(f'{ DIR_PATH }/static/Unfolded.html', 'r').read()

	return flask.render_template('flask/pagedjs.html', publication_unfolded=publication_unfolded, STYLESHEET=STYLESHEET)

@APP.route('/inspect/', methods=['GET', 'POST'])
def inspect():
	download(STYLESHEET) # download the stylesheet pad
	publication_unfolded = open(f'{ DIR_PATH }/static/Unfolded.html', 'r').read()

	return flask.render_template('flask/inspect.html', publication_unfolded=publication_unfolded, STYLESHEET=STYLESHEET)

@APP.route('/stylesheet/', methods=['GET'])
def stylesheet():
	return flask.render_template('flask/stylesheet.html')

if __name__ == '__main__':
	APP.debug=True
	APP.run(port=f'{ PORTNUMBER }')