from flask import Blueprint, flash, redirect, render_template, url_for
from flask_login import current_user, login_required
from flask_mailman import EmailMessage
from sqlalchemy import select

from web_application import db
from web_application.models import Bolum, Hat

st_hat = Blueprint(
    "st_hat",
    __name__,
    template_folder="templates",
    static_folder="static",
    url_prefix="/hatlar",
)


@st_hat.route("/bolum/<int:bolum_id>/hatlar")
@login_required
def index(bolum_id):
    bolum = (
        db.session.execute(select(Bolum).where(Bolum.id == bolum_id)).scalars().first()
    )
    data = {
        "title": f"{bolum.adi}",
        "subtitle": f"{bolum.adi} bölümündeki aktif üretim hatları",
        "hatlar": bolum.hatlar,
    }
    return render_template("hat/index.html", **data)


@st_hat.route("/<int:hat_id>")
@login_required
def hat_detay(hat_id):
    hat = db.session.execute(select(Hat).where(Hat.id == hat_id)).scalars().first()
    try:
        if hat:
            data = {
                "title": f"{hat.bolum.adi} - {hat.adi}",
                "subtitle": f"{hat.bolum.adi} - {hat.adi} için aktif üretim hatları",
                "hat": hat,
            }
        return render_template("hat/detail.html", **data)
    except Exception as e:
        flash(f"Bir hata oluştu: {str(e)}", "danger")
        return redirect(url_for("st_hat.index", bolum_id=hat.bolum_id))


@st_hat.route("/<int:hat_id>/aykiri-deger")
@login_required
def aykiri_deger_goster(hat_id):
    hat = db.session.execute(select(Hat).where(Hat.id == hat_id)).scalars().first()
    data = {
        "title": f"{hat.bolum.adi} - {hat.adi}",
        "subtitle": f"{hat.bolum.adi} - {hat.adi} için farklı algoritmalar tarafından gözlemlenen son 5 aykırı deger.",
        "hat": hat,
    }
    return render_template("hat/aykiri-degerler.html", **data)
