from flask import Response, render_template, flash, redirect, url_for
from flask.typing import ResponseReturnValue
from flask_wtf import FlaskForm
from wtforms import SubmitField

from app.extensions import db
from app.models import AbstractResource
from app.models.activity import Activity


def response_404(message: str) -> ResponseReturnValue:
    return Response(render_template("error.html.j2",
                                    header="404 Not Found",
                                    message=message))


def view_lifecycle(*,
                   header: str,
                   message: str,
                   success_message: str,
                   success_view: str,
                   section: str,
                   resource: AbstractResource,
                   action: str) -> ResponseReturnValue:
    form = LifecycleForm()
    if action == "destroy":
        form.submit.render_kw = {"class": "btn btn-danger"}
    elif action == "deprecate":
        form.submit.render_kw = {"class": "btn btn-warning"}
    elif action == "kick":
        form.submit.render_kw = {"class": "btn btn-success"}
    if form.validate_on_submit():
        if action == "destroy":
            resource.destroy()
        elif action == "deprecate":
            resource.deprecate(reason="manual")
        elif action == "kick":
            resource.kick()
        else:
            flash("Unknown action")
            return redirect(url_for("portal.portal_home"))
        activity = Activity(
            activity_type="lifecycle",
            text=f"Portal action: {message}. {success_message}"
        )
        db.session.add(activity)
        db.session.commit()
        activity.notify()
        flash(success_message, "success")
        return redirect(url_for(success_view))
    return render_template("lifecycle.html.j2",
                           header=header,
                           message=message,
                           section=section,
                           form=form)


class LifecycleForm(FlaskForm):  # type: ignore
    submit = SubmitField('Confirm')
