1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
use std::ffi::CString;

use spring_ai_sys::{COMMAND_TO_ID_ENGINE, MAX_RESPONSE_SIZE};

use crate::ai_interface::{
    callback::{
        command::{
            command_data::{
                lua::{CallLuaRulesCommandData, CallLuaUICommandData},
                CommandData,
            },
            command_topic::CommandTopic,
        },
        engine::handle_command,
    },
    AIInterface,
};

pub struct Lua {
    pub ai_id: i32,
}

impl AIInterface {
    pub fn lua(&self) -> Lua {
        Lua { ai_id: self.ai_id }
    }
}

impl Lua {
    pub fn call_rules(&self, in_data: &str) -> Result<String, String> {
        let in_data_cstring = CString::new(in_data).map_err(|e| format!("{e}"))?;

        let mut command_data = CallLuaRulesCommandData {
            in_data: in_data_cstring,
            in_size: in_data.len() as i32,
            out_data: CString::new(String::with_capacity(MAX_RESPONSE_SIZE as usize))
                .map_err(|e| format!("{e}"))?,
        };

        handle_command(
            self.ai_id,
            COMMAND_TO_ID_ENGINE,
            -1,
            CommandTopic::CallLuaRules.into(),
            &mut command_data.c_data(),
        )?;

        Ok(command_data.out_data.to_string_lossy().to_string())
    }
    pub fn call_ui(&self, in_data: &str) -> Result<String, String> {
        let in_data_cstring = CString::new(in_data).map_err(|e| format!("{e}"))?;

        let mut command_data = CallLuaUICommandData {
            in_data: in_data_cstring,
            in_size: in_data.len() as i32,
            out_data: CString::new(String::with_capacity(MAX_RESPONSE_SIZE as usize))
                .map_err(|e| format!("{e}"))?,
        };

        handle_command(
            self.ai_id,
            COMMAND_TO_ID_ENGINE,
            -1,
            CommandTopic::CallLuaUI.into(),
            &mut command_data.c_data(),
        )?;

        Ok(command_data.out_data.to_string_lossy().to_string())
    }
}