use std::str::FromStr;
use crate::rhai_engine::RhaiEngine;
use hdi::prelude::AgentPubKeyB64;
use hdi::prelude::{AgentPubKey, Record, Signature};
use hdk::prelude::SerializedBytes;
use hdk::prelude::UnsafeBytes;
use rhai::Array;
use rhai::{EvalAltResult, Map, Position};
use rmp_serde;
pub fn try_into_record(record: Map) -> Result<Record, Box<EvalAltResult>> {
let json = RhaiEngine::rhai_map_to_json(record);
let bytes = rmp_serde::to_vec(&json).map_err(|e| {
Box::new(EvalAltResult::ErrorRuntime(
format!("Failed to serialize record: {e}").into(),
Position::NONE,
))
})?;
let bytes = SerializedBytes::from(UnsafeBytes::from(bytes));
Record::try_from(bytes).map_err(|e| {
Box::new(EvalAltResult::ErrorRuntime(
format!("Failed to convert to Record: {e}").into(),
Position::NONE,
))
})
}
pub fn _try_into_agent_pubkey(bytes: Array) -> Result<AgentPubKey, Box<EvalAltResult>> {
AgentPubKey::try_from_raw_39(
bytes
.iter()
.map(|b| b.as_int().unwrap_or(0) as u8)
.collect::<Vec<u8>>(),
)
.map_err(|e| {
Box::new(EvalAltResult::ErrorRuntime(
format!("Invalid agent key: {e}").into(),
Position::NONE,
))
})
}
pub fn try_from_string_to_agent_pubkey(string: String) -> Result<AgentPubKey, Box<EvalAltResult>> {
AgentPubKeyB64::from_str(&string)
.map_err(|e| {
Box::new(EvalAltResult::ErrorRuntime(
format!("Invalid agent key: {e}").into(),
Position::NONE,
))
})
.map(|hash| hash.into())
}
pub fn try_into_signature(bytes: Array) -> Result<Signature, Box<EvalAltResult>> {
let signature_bytes: [u8; 64] = bytes
.iter()
.map(|b| b.as_int().unwrap_or(0) as u8)
.collect::<Vec<u8>>()
.try_into()
.map_err(|_| {
Box::new(EvalAltResult::ErrorRuntime(
"Invalid signature length".into(),
Position::NONE,
))
})?;
Ok(Signature::from(signature_bytes))
}