from wtforms import SubmitField, StringField, FloatField, HiddenField, validators, Form
from flask_wtf import FlaskForm
from flask import request, render_template, redirect
from main import db, app, ma
from sqlalchemy import Sequence
from sqlalchemy.exc import SQLAlchemyError
from status import st, Status

################################################################################
# Class describing Settings in the database, and via sqlalchemy, connected to the DB as well
################################################################################
class Settings(db.Model):
    id = db.Column(db.Integer, db.Sequence('settings_id_seq'), primary_key=True )
    import_path = db.Column(db.String)
    storage_path = db.Column(db.String)

    def __repr__(self):
        return f"<id: {self.id}, import_path: {self.import_path}, storage_path: {self.storage_path}>"

################################################################################
# Helper class that inherits a .dump() method to turn class Settings into json / useful in jinja2
################################################################################
class SettingsSchema(ma.SQLAlchemyAutoSchema):
    class Meta:
        model = Settings
        ordered = True

settings_schema = SettingsSchema(many=True)

################################################################################
# Helper class that defines a form for Settings, used to make html <form>
# with field validation (via wtforms)
################################################################################
class SettingsForm(FlaskForm):
    id = HiddenField()
    import_path = StringField('Path(s) to import from:', [validators.DataRequired()])
    storage_path = StringField('Path to store sorted images to:', [validators.DataRequired()])
    submit = SubmitField('Save' )

################################################################################
# /settings -> show current settings
################################################################################
@app.route("/settings", methods=["GET", "POST"])
def settings():
    form = SettingsForm(request.form)
    page_title='Settings'
    if request.method == 'POST' and form.validate():
        try:
			# HACK, I don't really need an id here, but sqlalchemy get weird
			# without one, so just grab the id of the only row there, it will
			# do...
            id = Settings.query.all()[0].id
            s = Settings.query.get(id)
            if 'submit' in request.form:
                st.SetMessage("Successfully Updated Settings" )
                s.import_path = request.form['import_path']
                s.storage_path = request.form['storage_path']
            db.session.commit()
            return redirect( '/settings' )
        except SQLAlchemyError as e:
            st.SetAlert( "danger" )
            st.SetMessage( "<b>Failed to modify Setting:</b>&nbsp;{}".format(e.orig) )
            return render_template("settings.html", form=form, page_title=page_title)
    else:
        form = SettingsForm( obj=Settings.query.first() )
        return render_template("settings.html", form=form, page_title = page_title)
