from datetime import datetime

from flask import render_template, url_for, flash, redirect, Response, Blueprint
from flask.typing import ResponseReturnValue
from flask_wtf import FlaskForm
import sqlalchemy
from wtforms import StringField, BooleanField, SubmitField
from wtforms.validators import DataRequired

from app.extensions import db
from app.models.base import Group

bp = Blueprint("group", __name__)


class NewGroupForm(FlaskForm):  # type: ignore
    group_name = StringField("Short Name", validators=[DataRequired()])
    description = StringField("Description", validators=[DataRequired()])
    eotk = BooleanField("Deploy EOTK instances?")
    submit = SubmitField('Save Changes', render_kw={"class": "btn btn-success"})


class EditGroupForm(FlaskForm):  # type: ignore
    description = StringField('Description', validators=[DataRequired()])
    eotk = BooleanField("Deploy EOTK instances?")
    submit = SubmitField('Save Changes', render_kw={"class": "btn btn-success"})


@bp.route("/list")
def group_list() -> ResponseReturnValue:
    groups = Group.query.order_by(Group.group_name).all()
    return render_template("list.html.j2",
                           section="group",
                           title="Groups",
                           item="group",
                           items=groups,
                           new_link=url_for("portal.group.group_new"))


@bp.route("/new", methods=['GET', 'POST'])
def group_new() -> ResponseReturnValue:
    form = NewGroupForm()
    if form.validate_on_submit():
        group = Group()
        group.group_name = form.group_name.data
        group.description = form.description.data
        group.eotk = form.eotk.data
        group.created = datetime.utcnow()
        group.updated = datetime.utcnow()
        try:
            db.session.add(group)
            db.session.commit()
            flash(f"Created new group {group.group_name}.", "success")
            return redirect(url_for("portal.group.group_edit", group_id=group.id))
        except sqlalchemy.exc.SQLAlchemyError:
            flash("Failed to create new group.", "danger")
            return redirect(url_for("portal.group.group_list"))
    return render_template("new.html.j2", section="group", form=form)


@bp.route('/edit/<group_id>', methods=['GET', 'POST'])
def group_edit(group_id: int) -> ResponseReturnValue:
    group = Group.query.filter(Group.id == group_id).first()
    if group is None:
        return Response(render_template("error.html.j2",
                                        section="group",
                                        header="404 Group Not Found",
                                        message="The requested group could not be found."),
                        status=404)
    form = EditGroupForm(description=group.description,
                         eotk=group.eotk)
    if form.validate_on_submit():
        group.description = form.description.data
        group.eotk = form.eotk.data
        group.updated = datetime.utcnow()
        try:
            db.session.commit()
            flash("Saved changes to group.", "success")
        except sqlalchemy.exc.SQLAlchemyError:
            flash("An error occurred saving the changes to the group.", "danger")
    return render_template("group.html.j2",
                           section="group",
                           group=group, form=form)
