from wtforms import SubmitField, StringField, 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
from refimg import Refimg

################################################################################
# Class describing Person in the database, and via sqlalchemy, connected to the DB as well
################################################################################
class PersonRefimgLink(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)


class Person(db.Model):
    id = db.Column(db.Integer, db.Sequence('person_id_seq'), primary_key=True )
    tag = db.Column(db.String(48), unique=False, nullable=False)
    surname = db.Column(db.String(48), unique=False, nullable=False)
    firstname = db.Column(db.String(48), unique=False, nullable=False)
    refimg = db.relationship('Refimg', secondary=PersonRefimgLink.__table__)

    def __repr__(self):
        return "<tag: {}, firstname: {}, surname: {}, refimg: {}>".format(self.tag,self.firstname, self.surname, self.refimg)

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

################################################################################
# Helper class that defines a form for person, used to make html <form>, with field validation (via wtforms)
################################################################################
class PersonForm(FlaskForm):
    id = HiddenField()
    tag = StringField('Tag (searchable name):', [validators.DataRequired()])
    firstname = StringField('FirstName(s):', [validators.DataRequired()])
    surname = StringField('Surname:', [validators.DataRequired()])
    submit = SubmitField('Save' )
    delete = SubmitField('Delete' )

################################################################################
# Routes for person data
#
# /persons -> GET only -> prints out list of all persons
################################################################################
@app.route("/persons", methods=["GET"])
def persons():
    persons = Person.query.all()
    return render_template("persons.html", persons=persons)
 

################################################################################
# /person -> GET/POST -> creates a new person type and when created, takes you back to /persons
################################################################################
@app.route("/person", methods=["GET", "POST"])
def new_person():
    form = PersonForm(request.form)
    page_title='Create new Person'
    reference_imgs = Refimg.query.all()

    if 'surname' not in request.form:
        return render_template("person.html", reference_imgs=reference_imgs, form=form, page_title=page_title )
    else:
        person = Person( tag=request.form["tag"], surname=request.form["surname"], firstname=request.form["firstname"] )
        try:
            db.session.add(person)
            db.session.commit()
            print(person)
            st.SetMessage( "Created new Person ({})".format(person.tag) )
            return redirect( '/persons' )
        except SQLAlchemyError as e:
            st.SetAlert( "danger" )
            st.SetMessage( "<b>Failed to add Person:</b>&nbsp;{}".format(e.orig) )
            return render_template("person.html", object=person, form=form, reference_imgs=reference_imgs, page_title = page_title)

################################################################################
# /person/<id> -> GET/POST(save or delete) -> shows/edits/delets a single
# person
################################################################################
@app.route("/person/<id>", methods=["GET", "POST"])
def person(id):
    form = PersonForm(request.form)
    page_title='Edit Person'
    reference_imgs = Refimg.query.all()
    
    if request.method == 'POST':
        try:
            person = Person.query.get(id)
            if 'delete' in request.form:
                st.SetMessage("Successfully deleted Person: ({})".format( person.tag ) )
                person = Person.query.filter(Person.id==id).delete()
            if 'submit' in request.form and form.validate():
                st.SetMessage("Successfully Updated Person: (From: {}, {}, {})".format(person.tag, person.firstname, person.surname) )
                person.tag = request.form['tag']
                person.surname = request.form['surname']
                person.firstname = request.form['firstname']
                person.refimg =[]
                for ref_img in reference_imgs:
                    if "ref-img-id-{}".format(ref_img.id) in request.form:
                        print('{} was checked, id: {}'.format(ref_img.fname, ref_img.id))
                        person.refimg.append(ref_img)

                st.AppendMessage(" To: ({}, {}, {})".format(person.tag, person.firstname, person.surname) )
            db.session.commit()
            return redirect( '/persons' )
        except SQLAlchemyError as e:
            st.SetAlert( "danger" )
            st.SetMessage( "<b>Failed to modify Person:</b>&nbsp;{}".format(e) )
            return render_template("person.html", form=form, reference_imgs="test", page_title=page_title)
    else:
        person = Person.query.get(id)
        print(person)
        form = PersonForm(request.values, obj=person)
    return render_template("person.html", object=person, form=form, reference_imgs=reference_imgs, page_title = page_title)
