// use rocket macros globally
#[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, QMediaType, MediaType };

// Equivalent to main()
#[rocket::main] // enable asyn 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
        // constructs FileServer with Path
        .mount("/", routes![index, fileserver])

        //FileServer unable to set Mime-Types
        // .mount("/", FileServer::from(relative!("templates/assets"))) 

        .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 static files from Index.html
    // 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> {
    // set path to static files
    let mut path = Path::new(relative!("templates/assets")).join(path);
    // if path exists add path to index.html ?
    let accept = vec![
        MediaType::CSS.into(), MediaType::JavaScript.into(),
    ];

    if path.is_dir() {
        path.push("templates/index.html");
        Accept::new(accept);
    }

    // open file readonly
    // NamedFile = Response
    println!("{:?}", path);
    NamedFile::open(path).await.ok()
}