from wtforms import SubmitField, StringField, HiddenField, FileField, 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
import os

################################################################################
# Class describing Refimg in the database, and via sqlalchemy, connected to the DB as well
################################################################################
class Refimg(db.Model):
    id = db.Column(db.Integer, db.Sequence('refimg_id_seq'), primary_key=True )
    fname = db.Column(db.String(256), unique=True, nullable=False)

    def __repr__(self):
        return "<id: {}, fname: {}>".format(self.id, self.fname )
        
#class Person_Refimg_Link(db.Model):
#    __tablename__ = "person_refimg_link"
#    person_id = db.Column(db.Integer, db.ForeignKey('person.id'), unique=True, nullable=False, primary_key=True)
#    refimg_id = db.Column(db.Integer, db.ForeignKey('refimg.id'), unique=True, nullable=False, primary_key=True)
#
#    def __repr__(self):
#        return "<person_id: {}, refimg_id>".format(self.person_id, self.refimg_id)

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

################################################################################
# Helper class that defines a form for refimg, used to make html <form>, with field validation (via wtforms)
################################################################################
class RefimgForm(FlaskForm):
    id = HiddenField()
    fname = StringField('File name:', [validators.DataRequired()])
    refimg_file = FileField('File name:')
    submit = SubmitField('Save' )
    delete = SubmitField('Delete' )

################################################################################
# Routes for refimg data
#
# /refimgs -> GET only -> prints out list of all refimgs
################################################################################
@app.route("/refimgs", methods=["GET"])
def refimgs():
    refimgs = Refimg.query.all()
    return render_template("refimgs.html", refimgs=refimgs)
 
################################################################################
# /refimg -> GET/POST -> creates a new refimg type and when created, takes you back to /refimgs
################################################################################
@app.route("/refimg", methods=["GET", "POST"])
def new_refimg():
    form = RefimgForm(request.form)
    page_title='Create new Reference Image'
    if request.method == 'GET':
        return render_template("refimg.html", form=form, page_title=page_title )
    else:
        # now save into the DB
        refimg = Refimg( fname=request.form["fname"] )
        try:
            # save the actual uploaded image to reference_images/
            f=request.files['refimg_file']
            f.save(os.path.join("reference_images", request.form["fname"]))
            db.session.add(refimg)
            db.session.commit()
            st.SetMessage( "Created new Refimg ({})".format(refimg.fname) )
            return redirect( '/refimgs' )
        except SQLAlchemyError as e:
            st.SetAlert( "danger" )
            st.SetMessage( "<b>Failed to add Refimg:</b>&nbsp;{}".format(e.orig) )
        except Exception as e:
            st.SetAlert( "danger" )
            st.SetMessage( "<b>Failed to modify Refimg:</b>&nbsp;{}".format(e) )
    return render_template("refimg.html", form=form, page_title=page_title)

################################################################################
# /refimg/<id> -> GET/POST(save or delete) -> shows/edits/delets a single
# refimg
################################################################################
@app.route("/refimg/<id>", methods=["GET", "POST"])
def refimg(id):
    form = RefimgForm(request.form)
    page_title='Edit Reference Image'
    if request.method == 'POST':
        try:
            refimg = Refimg.query.get(id)
            os.remove("reference_images/{}".format(refimg.fname) )
            if 'delete' in request.form:
                st.SetMessage("Successfully deleted Refimg: ({})".format( refimg.fname ) )
                refimg = Refimg.query.filter(Refimg.id==id).delete()
            if 'submit' in request.form and form.validate():
                st.SetMessage("Successfully Updated Refimg: (From: {})".format(refimg.fname))
                refimg.fname = request.form['fname']
                st.AppendMessage(" To: ({})".format(refimg.fname) )
                # save the actual uploaded image to reference_images/
                f=request.files['refimg_file']
                f.save(os.path.join("reference_images", request.form["fname"]))
            db.session.commit()
            return redirect( '/refimgs' )
        except SQLAlchemyError as e:
            st.SetAlert( "danger" )
            st.SetMessage( "<b>Failed to modify Refimg:</b>&nbsp;{}".format(e.orig) )
        except Exception as e:
            st.SetAlert( "danger" )
            st.SetMessage( "<b>Failed to modify Refimg:</b>&nbsp;{}".format(e) )
        return render_template("refimg.html", form=form, page_title=page_title)
    else:
        refimg = Refimg.query.get(id)
        form = RefimgForm(request.values, obj=refimg)
    return render_template("refimg.html", object=refimg, form=form, page_title = page_title)
