use crate::cache::{get_hash, get_str};
use cal_core::{AccountLite, Region};
use redis::aio::MultiplexedConnection;
use redis::AsyncCommands;

pub async fn get_account_by_ident_lite(
    con: MultiplexedConnection,
    key: &str,
) -> Option<AccountLite> {
    let result = get_hash(con.clone(), "cb:accounts", key).await;
    match result {
        None => None,
        Some(value) => {
            get_account_by_id_lite(con.clone(), value.clone()).await
        }
    }
}

pub async fn get_account_by_id_lite(con: MultiplexedConnection, key: String) -> Option<AccountLite> {
    let _key = format!("cb:account:{}", key);
    let result = get_str(con, &_key).await;
    match result {
        None => None,
        Some(value) => {
            let account: AccountLite = serde_json::from_str(&value).unwrap();
            Some(account)
        }
    }
}


pub async fn insert_account(mut con: MultiplexedConnection, account: AccountLite) {
    let key = format!("cb:region:{}", account.get_id_string());
    let value = serde_json::to_string(&account).unwrap();
    if let Err(e) = con.set::<String, String, String>(key, value).await {
        println!("Cache Error - Could not insert Region: {}", e);
    };
}

pub async fn insert_account_idents(mut con: MultiplexedConnection, items: Vec<(String, String)>) {
    if let Err(e) = con
        .hset_multiple::<&str, String, String, String>("cb:regions", &*items)
        .await
    {
        println!("Cache Error {:?}", e);
    }
}