use crate::{display::format_table, ham::Ham, CommonOpts};
use anyhow::Result;
use colored::Colorize;
use holochain_types::dna::ActionHash;
use rave_engine::types::entries::{CodeTemplateExt, RAVE};
use rave_engine::types::Transaction;

pub async fn execute_rave(value: CommonOpts, input: String) -> Result<()> {
    let agent = Ham::connect(value).await?;

    // Parse the input JSON string into the expected input type
    let input: serde_json::Value = serde_json::from_str(&input)?;

    let result: (RAVE, ActionHash) = agent
        .zome_call("alliance", "transactor", "execute", input)
        .await?;

    println!("===================");
    println!("RAVE Executed:");
    println!("RAVE: {:#?}", result.0);
    println!("Action Hash: {:#?}", result.1);
    println!("===================");

    Ok(())
}

pub async fn get_incoming_raves(value: CommonOpts) -> Result<()> {
    let agent = Ham::connect(value).await?;

    let raves: Vec<Transaction> = agent
        .zome_call("alliance", "transactor", "get_incoming_raves", ())
        .await?;

    println!("===================");
    println!("Incoming RAVEs:");
    println!("{:#?}", raves);
    println!("===================");

    Ok(())
}

pub async fn collect_from_rave(value: CommonOpts, rave: String) -> Result<()> {
    let agent = Ham::connect(value).await?;

    // Parse the input JSON string into Transaction
    let rave: serde_json::Value = serde_json::from_str(&rave)?;

    let result: Transaction = agent
        .zome_call("alliance", "transactor", "collect_from_rave", rave)
        .await?;

    println!("===================");
    println!("RAVE Accepted:");
    println!("{:#?}", result);
    println!("===================");

    Ok(())
}

pub async fn get_code_templates_lib(value: CommonOpts) -> Result<Vec<CodeTemplateExt>> {
    let agent = Ham::connect(value).await?;

    let raves: Vec<CodeTemplateExt> = agent
        .zome_call("alliance", "transactor", "get_code_templates_lib", ())
        .await?;

    println!("Code Templates Library:");
    if !raves.is_empty() {
        let table = format_table(&raves, "Code Templates Library");
        table.printstd();
    } else {
        println!("{}", "No code templates library".dimmed());
    }

    Ok(raves)
}
