from flask import Blueprint, render_template
import os
from flask import *
# from flask_session import Session
import secrets


def make_token():
    return secrets.token_urlsafe(4)


pca_radar = Blueprint('pca_radar', __name__,
                      template_folder=os.path.join('templates'))


@pca_radar.route('/cheminfo/pca')
def render_cheminfo_pca_input():
    return render_template('cheminfo.pca_radar.html')


@pca_radar.route('/cheminfo/input_process', methods=['POST'])
def get_sdf_for_pca_radar():
    file = request.files['file']
    if not file.filename.endswith('.sdf'):
        return render_template('cheminfo.pca_radar.html', error="not an sdf")
    else:
        session['pca_token'] = make_token()
        if not os.path.exists(os.path.join(current_app.root_path, 'Cheminformatics', 'pca_radar', session.get("pca_token"))):
            os.makedirs(os.path.join(current_app.root_path,
                                     'Cheminformatics', 'pca_radar', session.get("pca_token")))

        file.save(os.path.join(current_app.root_path,
                               'Cheminformatics', 'pca_radar', session.get("pca_token"), file.filename))

        from Cheminformatics.pca_radar.run_notebook import run_with_pm

        result = run_with_pm(os.path.join(current_app.root_path, 'Cheminformatics', 'pca_radar', session.get(
            "pca_token"), file.filename), session.get("pca_token"))
        if result is True:
            return render_template(f"{session.get('pca_token')}_output.html")


@pca_radar.route('/pca_r_download/<file>')
def pca_downloads(file):
    return send_file(os.path.join(current_app.root_path, "Cheminformatics", "pca_radar", file))
