from flask import Flask, render_template, request, redirect, jsonify
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.exc import SQLAlchemyError
from flask_marshmallow import Marshmallow
from flask_bootstrap import Bootstrap
from wtforms import SubmitField, StringField, HiddenField, SelectField, IntegerField, TextAreaField, validators
from flask_wtf import FlaskForm
from status import st, Status
from shared import CreateSelect, DB_URL
import re
import socket

####################################### Flask App globals #######################################
PROD_HOST="pa_web"
hostname = socket.gethostname()
print( "Running on: {}".format( hostname) )
app = Flask(__name__)
### what is this value? I gather I should change it?

app.config['SQLALCHEMY_DATABASE_URI'] = DB_URL
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config.from_mapping( SECRET_KEY=b'\xd6\x04\xbdj\xfe\xed$c\x1e@\xad\x0f\x13,@G')
db = SQLAlchemy(app)
ma = Marshmallow(app)
Bootstrap(app)

################################# Now, import non-book classes ###################################
from settings import Settings
from files import Entry
from person import Person
from refimg import Refimg
from job import Job, GetNumActiveJobs
from ai import *

####################################### CLASSES / DB model #######################################

class PA_JobManager_Message(db.Model):
    __tablename__ = "pa_job_manager_fe_message"
    id = db.Column(db.Integer, db.Sequence('pa_job_manager_fe_message_id_seq'), primary_key=True )
    job_id = db.Column(db.Integer, db.ForeignKey('job.id') )
    alert = db.Column(db.String)
    message = db.Column(db.String)
    def __repr__(self):
        return "<id: {}, job_id: {}, alert: {}, message: {}".format(self.id, self.job_id, self.alert, self.message)

def GetJM_Message():
    msg=PA_JobManager_Message.query.first()
    return msg

def ClearJM_Message(id):
    msg=PA_JobManager_Message.query.get(id)
    PA_JobManager_Message.query.filter(PA_JobManager_Message.id==id).delete()
    db.session.commit()
    return


####################################### GLOBALS #######################################
# allow jinja2 to call these python functions directly
app.jinja_env.globals['ClearStatus'] = st.ClearStatus
app.jinja_env.globals['GetAlert'] = st.GetAlert
app.jinja_env.globals['GetMessage'] = st.GetMessage
app.jinja_env.globals['GetNumActiveJobs'] = GetNumActiveJobs
app.jinja_env.globals['GetJM_Message'] = GetJM_Message
app.jinja_env.globals['ClearJM_Message'] = ClearJM_Message
app.jinja_env.globals['CreateSelect'] = CreateSelect

# default page, just the navbar
@app.route("/", methods=["GET"])
def main_page():
    return render_template("base.html")

if __name__ == "__main__":
    if hostname == PROD_HOST:
        app.run(ssl_context=('/etc/letsencrypt/live/book.depaoli.id.au/cert.pem', '/etc/letsencrypt/live/book.depaoli.id.au/privkey.pem'), host="0.0.0.0", debug=False)
    else:
        app.run(host="0.0.0.0", debug=True)
