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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
use rustsynth_sys as ffi;
use std::ffi::{CStr, CString};
use std::fs::File;
use std::io::Read;
use std::ops::{Deref, DerefMut};
use std::path::Path;
use std::ptr;
use std::ptr::NonNull;

use crate::core::CoreRef;
use crate::map::Map;
use crate::node::Node;
use crate::vsscript::errors::Result;
use crate::vsscript::*;

use crate::vsscript::VSScriptError;

/// Contains two possible variants of arguments to `Environment::evaluate_script()`.
#[derive(Clone, Copy)]
enum EvaluateScriptArgs<'a> {
    /// Evaluate a script contained in the string.
    Script(&'a str),
    /// Evaluate a script contained in the file.
    File(&'a Path),
}

/// A wrapper for the VSScript environment.
#[derive(Debug)]
pub struct Environment {
    handle: NonNull<ffi::VSScript>,
}

unsafe impl Send for Environment {}
unsafe impl Sync for Environment {}

impl Drop for Environment {
    #[inline]
    fn drop(&mut self) {
        unsafe {
            ScriptAPI::get_cached().free_script(self.handle.as_ptr());
        }
    }
}

impl Environment {
    /// Retrieves the VSScript error message.
    ///
    /// # Safety
    /// This function must only be called if an error is present.
    #[inline]
    unsafe fn error(&self) -> Option<CString> {
        let message = ScriptAPI::get_cached().get_error(self.handle.as_ptr());
        if message.is_null() {
            None
        } else {
            Some(CStr::from_ptr(message).to_owned())
        }
    }

    /// Creates an empty script environment.
    ///
    /// Useful if it is necessary to set some variable in the script environment before evaluating
    /// any scripts.
    pub fn new(core: &CoreRef) -> Result<Self> {
        let api = ScriptAPI::get().unwrap();

        let handle = unsafe { api.create_script(core.ptr()) };
        let environment = Self {
            handle: unsafe { NonNull::new_unchecked(handle) },
        };

        match unsafe { environment.error() } {
            None => Ok(environment),
            Some(error) => Err(VSScriptError::new(error).into()),
        }
    }

    /// Calls `ScriptAPI::eval_buffer()`.
    fn evaluate_script(&self, args: EvaluateScriptArgs) -> Result<()> {
        let (script, path) = match args {
            EvaluateScriptArgs::Script(script) => (script.to_owned(), None),
            EvaluateScriptArgs::File(path) => {
                let mut file = File::open(path).map_err(Error::FileOpen)?;
                let mut script = String::new();
                file.read_to_string(&mut script).map_err(Error::FileRead)?;

                // vsscript throws an error if it's not valid UTF-8 anyway.
                let path = path.to_str().ok_or(Error::PathInvalidUnicode)?;
                let path = CString::new(path)?;

                (script, Some(path))
            }
        };

        let script = CString::new(script)?;

        let rv = unsafe {
            ScriptAPI::get_cached().eval_buffer(
                self.handle.as_ptr(),
                script.as_ptr(),
                path.as_ref().map(|p| p.as_ptr()).unwrap_or(ptr::null()),
            )
        };

        if rv != 0 {
            Err(VSScriptError::new(unsafe { self.error().unwrap() }).into())
        } else {
            Ok(())
        }
    }

    /// Creates a script environment and evaluates a script contained in a string.
    #[inline]
    pub fn from_script(core: &CoreRef, script: &str) -> Result<Self> {
        let environment = Self::new(core)?;
        environment.evaluate_script(EvaluateScriptArgs::Script(script))?;
        Ok(environment)
    }

    /// Creates a script environment and evaluates a script contained in a file.
    #[inline]
    pub fn from_file<P: AsRef<Path>>(core: &CoreRef, path: P) -> Result<Self> {
        let environment = Self::new(core)?;
        environment.evaluate_script(EvaluateScriptArgs::File(path.as_ref()))?;
        Ok(environment)
    }

    /// Evaluates a script contained in a string.
    #[inline]
    pub fn eval_script(&mut self, script: &str) -> Result<()> {
        self.evaluate_script(EvaluateScriptArgs::Script(script))
    }

    /// Evaluates a script contained in a file.
    #[inline]
    pub fn eval_file<P: AsRef<Path>>(&mut self, path: P) -> Result<()> {
        self.evaluate_script(EvaluateScriptArgs::File(path.as_ref()))
    }

    /// Retrieves a variable from the script environment.
    pub fn get_variable(&self, name: &str, map: &mut Map) -> Result<()> {
        let name = CString::new(name)?;
        let rv = unsafe {
            ScriptAPI::get_cached().get_variable(
                self.handle.as_ptr(),
                name.as_ptr(),
                map.deref_mut(),
            )
        };
        if rv != 0 {
            Err(Error::NoSuchVariable)
        } else {
            Ok(())
        }
    }

    /// Sets variables in the script environment.
    pub fn set_variables(&self, variables: &Map) -> Result<()> {
        let rv = unsafe {
            ScriptAPI::get_cached().set_variables(self.handle.as_ptr(), variables.deref())
        };
        if rv != 0 {
            Err(Error::NoSuchVariable)
        } else {
            Ok(())
        }
    }

    pub fn get_output(&self, index: usize) -> Option<Node<'_>> {
        let ptr = unsafe { ScriptAPI::get_cached().get_output(self.handle.as_ptr(), index as i32) };
        if ptr.is_null() {
            None
        } else {
            Some(unsafe { Node::from_ptr(ptr) })
        }
    }

    pub fn get_output_alpha(&self, index: usize) -> Option<Node<'_>> {
        let ptr =
            unsafe { ScriptAPI::get_cached().get_output_alpha(self.handle.as_ptr(), index as i32) };
        if ptr.is_null() {
            None
        } else {
            Some(unsafe { Node::from_ptr(ptr) })
        }
    }

    pub fn clear_output(&self, index: usize) -> Result<()> {
        todo!()
    }
}