use chrono::Utc;
use mysql_async::{Conn, Pool, error::Error};
use mysql_async::prelude::{params, Queryable};
use serde::Serialize;

use crate::db_types::{UBigInt, BigInt, Integer, VarChar};
use crate::auth;

#[derive(Serialize)]
pub struct Member {
    pub id: UBigInt,
    pub secret: VarChar,
    pub name: VarChar,
    pub joindate: BigInt,
    pub status: Integer,
    pub permissions: UBigInt,
}

pub async fn get_member_row(p: &Pool, uid: u64) -> Result<Option<Member>, Error> {
    let conn = p.get_conn().await?;
    type RowData = (VarChar, VarChar, BigInt, Integer, UBigInt);
    let (_, db_row) : (Conn, Option<RowData>) = conn.first_exec(
        "SELECT secret, name, joindate, status, permissions FROM members WHERE id = :id",
        params!{"id" => uid}
        ).await?;

    if let Some(row) = db_row {
        return Ok(Some(Member {
            id: uid,
            secret: row.0,
            name: row.1,
            joindate: row.2,
            status: row.3,
            permissions:4,
        }))
    }
    return Ok(None)
}

pub async fn insert_new_member(p: &Pool, name: VarChar, perms: u64) -> Result<Member, Error> {
    use crate::auth::generate_secret;

    let conn:   Conn   = p.get_conn().await?;
    let secret_raw: String = generate_secret();
    let secret = match bcrypt::hash(&secret_raw, auth::BCRYPT_COST) {
        Ok(value) => value,
        Err(e) => panic!("\tCould not insert member due to bcrypt failure:\n\t\t{}",e)
    };
    let now:    BigInt = Utc::now().timestamp();
    
    let conn = conn.drop_exec(
        "INSERT INTO members(secret, name, joindate, status, permissions)
        VALUES(:secret, :name, :joindate, :status, :permissions)", 
        mysql_async::params!{
            "secret" => secret.clone(),
            "name" => name.clone(),
            "joindate" => now,
            "status" => 0,
            "permissions" => perms
        }).await?;

    // now pull back the user from our db and return that row
    let db_row_result: (Conn, Option<UBigInt>) = conn.first_exec(
        "SELECT id FROM members WHERE secret = :secret", 
        params!{
            "secret" => secret.clone()
        }).await?;

    Ok(Member {
        id: db_row_result.1.unwrap(), // if we made it this far this shouldn't fail (i hope)
        secret: secret_raw,
        name: name,
        joindate: now,
        status: 0,
        permissions: perms
    })
}
