#![feature(proc_macro_hygiene, decl_macro)]

pub mod admin;
pub mod controllers;
pub mod misc;
pub mod models;
pub mod schema;

#[macro_use]
extern crate rocket;
#[macro_use]
extern crate diesel;
extern crate comrak;
extern crate dotenv;
extern crate rocket_contrib;
extern crate tera;

use comrak::{markdown_to_html, ComrakOptions};
use controllers::{get_post, get_posts, MAX_POSTS_PER_PAGE};
use misc::get_context;
use rocket::response::NamedFile;
use rocket::Request;
use rocket_contrib::serve::StaticFiles;
use rocket_contrib::templates::Template;
use std::path::Path;
use std::vec::Vec;

#[get("/?<page>")]
fn index(page: Option<i8>) -> Template {
    let page = page.unwrap_or(1);

    let mut context = get_context();

    let (posts, n_posts) = get_posts(page as i64);

    let total_pages = (n_posts as f64 / MAX_POSTS_PER_PAGE as f64).ceil() as i64;

    context.insert("posts", &posts);
    context.insert("total_pages", &total_pages);
    context.insert("actual_page", &page);
    Template::render("index", context)
}

#[get("/post/<title>")]
fn show_post(title: String) -> Template {
    let mut context = get_context();

    let title_splited: Vec<&str> = title.split('-').collect();
    let id = title_splited.last().unwrap().parse().unwrap_or(-1);

    match get_post(id) {
        Ok(mut post) => {
            let content = markdown_to_html(&post.content, &ComrakOptions::default());
            post.content = content;

            context.insert("post", &post);
            Template::render("post", context)
        }
        Err(_) => {
            let uri = format!("/post/{}", title_splited.join("-"));
            context.insert("url", &uri);
            Template::render("404", context)
        }
    }
}

#[catch(404)]
fn not_found_404(req: &Request) -> Template {
    let mut context = get_context();

    let uri = format!("{}", req.uri());

    context.insert("url", &uri);
    Template::render("404", context)
}

#[get("/favicon.ico")]
fn favicon() -> Option<NamedFile> {
    NamedFile::open(Path::new("static/favicon.ico")).ok()
}

fn main() {
    rocket::ignite()
        .attach(Template::fairing())
        .mount("/", routes![index, show_post, favicon])
        .mount("/admin", routes![admin::index])
        .mount("/static", StaticFiles::from("static"))
        .register(catchers![not_found_404])
        .launch();
}