#[macro_use] extern crate rocket;

// push strings to path
// generate path from strings
use std::path::{ PathBuf, Path };

// Responder Type NamedFile
// serve file with Content-Type based on name
use rocket::fs::{ NamedFile, relative };

// Set MIME-Types, Accept Header for Response
use rocket::http::{ Accept, MediaType };
use rocket::http::ContentType;

// Equivalent to main()
#[rocket::main] // enable async main()
async fn main() -> Result<(), rocket::Error> {
    
    // State Rocket<Build> => configuration
        // registering routes
        // mounting routes
        // registering/ mobuildunting catchers
        // manage State
        // attach Fairings
        rocket::build()
        // State Rocket<Ignite> => Finalized App ready to launch
            // check before launching
            // catch errors
        .mount("/", routes![ index, fileserver, experiments, perma, greentech ])

        .ignite().await?
        // State Rocket<Orbit> => Running App
            // State after launch() is called
            // launch() starts server
        .launch().await
}

// Configure requests
// generate routes, set attributes
    // set http method
    // set uri
#[route(GET, uri = "/")]
// if success call handler
async fn index() -> Option<NamedFile> {
   NamedFile::open("templates/index.html").await.ok()
}

// serve other pages (html GET)
// create routes for pages
#[get("/experiments")]
async fn experiments() -> Option<NamedFile> {
    NamedFile::open("templates/experiments.html").await.ok()
}

#[get("/permaculture")]
async fn perma() -> Option<NamedFile> {
    NamedFile::open("templates/permaculture.html").await.ok()
}

#[get("/greentech")]
async fn greentech() -> Option<NamedFile> {
    NamedFile::open("templates/greentech.html").await.ok()
}


// Serve static files from /
    // Match against multiple segments
    // parameters need to implement FromSegments
    // PathBuf implements FromSegments
    // push all segments to path
    // Option<Some, Err> implements Responder
    // NamedFile implements Responder => generates Response
#[route(GET, uri= "/<path..>")]
async fn fileserver(path: PathBuf) -> Option<NamedFile> { // PathBuf =  Heapstring, growable
    // set path to static files
    let mut path = Path::new(relative!("templates/assets")).join(path); // Path = stack string, fixed size
    // path accessible from /

    // Note: How to serve fontawesome ?
    if path.ends_with("all.css") {
        println!("Can not load fontawesome icons at: {:?}", path);
    }
    // Open file at path 
        NamedFile::open(path).await.ok()
}