use actix_web::{post, routes, web, HttpRequest, HttpResponse, Responder};
use log::info;
use serde::Deserialize;

use crate::template_utils::{render_template, Flash, FlashType, TemplateArgs};
use crate::SharedData;

#[derive(Clone, Debug, Deserialize)]
pub(crate) struct Mail {
    mail: String,
    subject: String,
    message: String,
}

#[routes]
#[get(r"/")]
#[get(r"/{filename:.*\.html}")]
pub(crate) async fn template(
    shared: web::Data<SharedData<'_>>,
    req: HttpRequest,
) -> actix_web::Result<impl Responder> {
    let path = match req.match_info().query("filename") {
        "" => "index",
        other => other
            .strip_suffix(".html")
            .expect("only paths with this suffix should get here"),
    };

    render_template(&shared.handlebars, path, &TemplateArgs::default())
        .map(|body| HttpResponse::Ok().body(body))
}

#[post("/mail.html")]
pub(crate) async fn mail_post(
    shared: web::Data<SharedData<'_>>,
    form: web::Form<Mail>,
) -> actix_web::Result<impl Responder> {
    info!("{:?}", form);

    let args = TemplateArgs::builder()
        .flash(Flash::new("Mail successfully sent!", FlashType::Success))
        .build();

    render_template(&shared.handlebars, "mail", &args).map(|body| HttpResponse::Ok().body(body))
}
