use axum::{
    response::{IntoResponse, Redirect},
    routing::{get, Router},
    Extension,
};
use sqlx::PgPool;
use std::error::Error;
use tower_http::services::ServeDir;

use crate::database::{
    link::{Link, LinkType},
    PsqlData,
};

use super::{
    books,
    posts::{self, get_articles_date_sorted},
    projects,
    templates::{
        AboutTemplate, AiTemplate, BlogrollTemplate, ContactTemplate, CookingTemplate,
        CreationTemplate, GiftsTemplate, HomeTemplate, HtmlTemplate, InterestsTemplate,
        LinksPageTemplate, MoneyTemplate, NowTemplate, TechnologyTemplate, TimeTemplate,
        UsesTemplate,
    },
};

pub fn get_router(pool: PgPool) -> Router {
    let assets_path = std::env::current_dir().unwrap();

    Router::new()
        .nest("/posts", posts::get_router())
        .nest("/projects", projects::get_router())
        .nest("/books", books::get_router())
        .nest_service(
            "/assets",
            ServeDir::new(format!("{}/assets", assets_path.to_str().unwrap())),
        )
        .route("/", get(home))
        .route("/now", get(now))
        .route("/about", get(about))
        .route("/contact", get(contact))
        .route("/uses", get(uses))
        .route("/ai", get(ai))
        .route("/blogroll", get(blogroll))
        .route("/links", get(links))
        .route("/interests", get(interests))
        .route("/gifts", get(gifts))
        .route("/time", get(time))
        .route("/cooking", get(cooking))
        .route("/creation", get(creation))
        .route("/technology", get(technology))
        .route("/money", get(money))
        .route(
            "/robots.txt",
            get(|| async { Redirect::permanent("/assets/robots.txt") }),
        )
        .route(
            "/feed.xml",
            get(|| async { Redirect::permanent("/assets/feed.xml") }),
        )
        .layer(Extension(pool))
}

async fn home(Extension(pool): Extension<PgPool>) -> impl IntoResponse {
    let mut articles = get_articles_date_sorted(&pool).await.unwrap();
    articles.truncate(5);
    HtmlTemplate(HomeTemplate {
        recent_articles: articles,
    })
}

async fn now() -> impl IntoResponse {
    HtmlTemplate(NowTemplate {})
}

async fn about() -> impl IntoResponse {
    HtmlTemplate(AboutTemplate {})
}

async fn contact() -> impl IntoResponse {
    HtmlTemplate(ContactTemplate {})
}

async fn uses() -> impl IntoResponse {
    HtmlTemplate(UsesTemplate {})
}

async fn ai() -> impl IntoResponse {
    HtmlTemplate(AiTemplate {})
}

async fn interests() -> impl IntoResponse {
    HtmlTemplate(InterestsTemplate {})
}

async fn gifts() -> impl IntoResponse {
    HtmlTemplate(GiftsTemplate {})
}

async fn blogroll(Extension(pool): Extension<PgPool>) -> impl IntoResponse {
    let blogroll_page = BlogrollTemplate {
        blogs: match get_links_as_list(&pool, LinkType::BLOG).await {
            Ok(list) => list,
            Err(_) => Vec::new(),
        },
    };
    HtmlTemplate(blogroll_page)
}

async fn links(Extension(pool): Extension<PgPool>) -> impl IntoResponse {
    let links_page = LinksPageTemplate {
        articles: match get_links_as_list(&pool, LinkType::ARTICLE).await {
            Ok(list) => list,
            Err(_) => Vec::new(),
        },
    };
    HtmlTemplate(links_page)
}

pub async fn get_links_as_list(
    pool: &PgPool,
    link_type: LinkType,
) -> Result<Vec<Link>, Box<dyn Error>> {
    let mut links: Vec<Link> = match Link::read_all(pool).await {
        Ok(a) => a.iter().map(|x| *x.clone()).collect(),
        Err(_) => Vec::new(),
    };

    links.sort_by(|a, b| b.date_added.cmp(&a.date_added));

    let list: Vec<Link> = links
        .into_iter()
        .filter(|link| link.link_type == link_type)
        .collect();
    Ok(list)
}

async fn time() -> impl IntoResponse {
    let time_page = TimeTemplate {};
    HtmlTemplate(time_page)
}

async fn cooking() -> impl IntoResponse {
    let cooking_page = CookingTemplate {};
    HtmlTemplate(cooking_page)
}

async fn creation() -> impl IntoResponse {
    let creation_page = CreationTemplate {};
    HtmlTemplate(creation_page)
}

async fn technology() -> impl IntoResponse {
    let technology_page = TechnologyTemplate {};
    HtmlTemplate(technology_page)
}

async fn money() -> impl IntoResponse {
    let money_page = MoneyTemplate {};
    HtmlTemplate(money_page)
}
