use rusqlite::Connection;

#[derive(Debug, Clone, RustcEncodable)]
pub struct Cocktail {
    pub name: String,
    pub image: String,
    pub created: String, // ::time::Timespec,

    pub tags: Vec<Tag>,
    pub ingredients: Vec<Ingredient>,
}


#[derive(Debug, Clone, RustcEncodable)]
pub struct Tag {
    pub name: String,
}

#[derive(Debug, Clone, RustcEncodable)]
pub struct Ingredient {
    pub name: String,
    pub amount: String,
}

pub fn get_cocktail_list(conn: &Connection) ->
    Result<Vec<Cocktail>, ::rusqlite::Error>
{
    let mut stmt = conn.prepare(
        "SELECT id, name, image, created FROM Cocktail ORDER BY created DESC")?;

    let cocktails: Result<Vec<(i64, Cocktail)>, ::rusqlite::Error> =
        stmt.query_and_then(&[], |row| {
            Ok((row.get_checked(0)?,
                Cocktail {
                    name: row.get_checked(1)?,
                    image: row.get_checked(2)?,
                    created: row.get_checked(3)?,

                    ingredients: vec![],
                    tags: vec![],
                }))
        })?.collect();

    let cocktails: Result<Vec<Cocktail>, ::rusqlite::Error> =
        cocktails?.iter().map(|&(id, ref c)| {
            let mut c = c.clone();
            let mut tag_stmt = conn.prepare(
                "SELECT name FROM Tag WHERE cocktail_id = ?")?;
            let tags: Result<Vec<Tag>, ::rusqlite::Error> =
                tag_stmt.query_and_then(&[&id], |row| {
                    Ok(Tag { name: row.get_checked(0)? })
                })?.collect();
            c.tags = tags?;
            Ok(c)
        }).collect();
    Ok(cocktails?)
}
