#![feature(plugin)]
#![plugin(rocket_codegen)]

extern crate glob;
extern crate rand;
extern crate rocket;
extern crate rocket_contrib;

#[macro_use]
extern crate serde_derive;

mod static_files;
// mod tunes;

use glob::glob;
use rand::Rng;
use rocket_contrib::Template;

#[derive(Serialize)]
struct IndexContext {
    title: String,
}

#[derive(Serialize)]
struct RandomContext {
    title: String,
    music_file: String,
    music_title: String,
    interval: u8,
}

#[get("/")]
fn index() -> Template {
    let context = IndexContext { title: String::from("Gäll de kennsch mi nit?") };

    Template::render("index", &context)
}

#[get("/random")]
fn random() -> Template {
    println!("looking for a random tune...");

    // let (file_name, file_title) = tunes::random_tune();

    let files = glob("static/sound/*.ogg")
        .expect("Failed to read glob pattern")
        .collect::<Vec<_>>();

    let chosen_one = match *rand::thread_rng().choose(&files).unwrap() {
        Ok(ref path) => path,
        Err(_) => panic!(""),
    };

    let file_name = chosen_one.file_name().unwrap().to_str().unwrap();
    let file_title = chosen_one.file_stem().unwrap().to_str().unwrap();

    let context = RandomContext {
        title: String::from(format!("♪ {}", file_title)),
        music_file: String::from(file_name),
        music_title: String::from(file_title),
        interval: 3,
    };

    Template::render("random", &context)
}

fn main() {
    rocket::ignite()
        .mount("/", routes![index, random])
        .mount("/static", routes![static_files::all])
        .launch();
}
