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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
#![allow(non_upper_case_globals)]
use std::{
    borrow::Cow,
    ffi::{CStr, CString},
    marker::PhantomData,
};

use obs_sys::{
    obs_data_array_count, obs_data_array_item, obs_data_array_release, obs_data_array_t,
    obs_data_clear, obs_data_create, obs_data_create_from_json, obs_data_create_from_json_file,
    obs_data_create_from_json_file_safe, obs_data_erase, obs_data_get_json, obs_data_item_byname,
    obs_data_item_get_array, obs_data_item_get_bool, obs_data_item_get_double,
    obs_data_item_get_int, obs_data_item_get_obj, obs_data_item_get_string, obs_data_item_gettype,
    obs_data_item_numtype, obs_data_item_release, obs_data_item_t, obs_data_number_type,
    obs_data_number_type_OBS_DATA_NUM_DOUBLE, obs_data_number_type_OBS_DATA_NUM_INT,
    obs_data_release, obs_data_set_default_bool, obs_data_set_default_double,
    obs_data_set_default_int, obs_data_set_default_obj, obs_data_set_default_string, obs_data_t,
    obs_data_type, obs_data_type_OBS_DATA_ARRAY, obs_data_type_OBS_DATA_BOOLEAN,
    obs_data_type_OBS_DATA_NUMBER, obs_data_type_OBS_DATA_OBJECT, obs_data_type_OBS_DATA_STRING,
    size_t,
};

use crate::{string::ObsString, wrapper::PtrWrapper};

#[derive(Debug, Eq, PartialEq, Copy, Clone)]
pub enum DataType {
    String,
    Int,
    Double,
    Boolean,
    /// Map container
    Object,
    /// Array container
    Array,
}

impl DataType {
    pub fn new(typ: obs_data_type, numtyp: obs_data_number_type) -> Self {
        match typ {
            obs_data_type_OBS_DATA_STRING => Self::String,
            obs_data_type_OBS_DATA_NUMBER => match numtyp {
                obs_data_number_type_OBS_DATA_NUM_INT => Self::Int,
                obs_data_number_type_OBS_DATA_NUM_DOUBLE => Self::Double,
                _ => unimplemented!(),
            },
            obs_data_type_OBS_DATA_BOOLEAN => Self::Boolean,
            obs_data_type_OBS_DATA_OBJECT => Self::Object,
            obs_data_type_OBS_DATA_ARRAY => Self::Array,
            _ => unimplemented!(),
        }
    }

    unsafe fn from_item(item_ptr: *mut obs_data_item_t) -> Self {
        let typ = obs_data_item_gettype(item_ptr);
        let numtyp = obs_data_item_numtype(item_ptr);
        Self::new(typ, numtyp)
    }
}

pub trait FromDataItem {
    fn typ() -> DataType;
    /// # Safety
    ///
    /// Pointer must be valid.
    unsafe fn from_item_unchecked(item: *mut obs_data_item_t) -> Self;

    /// # Safety
    ///
    /// Pointer must be valid.
    unsafe fn set_default_unchecked(obj: *mut obs_data_t, name: ObsString, val: Self);
}

impl FromDataItem for Cow<'_, str> {
    fn typ() -> DataType {
        DataType::String
    }
    unsafe fn from_item_unchecked(item: *mut obs_data_item_t) -> Self {
        let ptr = obs_data_item_get_string(item);
        CStr::from_ptr(ptr).to_string_lossy()
    }
    unsafe fn set_default_unchecked(obj: *mut obs_data_t, name: ObsString, val: Self) {
        let s = CString::new(val.as_ref()).unwrap();
        obs_data_set_default_string(obj, name.as_ptr(), s.as_ptr());
    }
}

macro_rules! impl_get_int {
    ($($t:ty)*) => {
        $(
            impl FromDataItem for $t {
                fn typ() -> DataType {
                    DataType::Int
                }
                unsafe fn from_item_unchecked(item: *mut obs_data_item_t) -> Self {
                    obs_data_item_get_int(item) as $t
                }
                unsafe fn set_default_unchecked(obj: *mut obs_data_t, name: ObsString, val: Self) {
                    obs_data_set_default_int(obj, name.as_ptr(), val as i64)
                }
            }
        )*
    };
}

impl_get_int!(i64 u64 i32 u32 i16 u16 i8 u8 isize usize);

impl FromDataItem for f64 {
    fn typ() -> DataType {
        DataType::Double
    }
    unsafe fn from_item_unchecked(item: *mut obs_data_item_t) -> Self {
        obs_data_item_get_double(item)
    }
    unsafe fn set_default_unchecked(obj: *mut obs_data_t, name: ObsString, val: Self) {
        obs_data_set_default_double(obj, name.as_ptr(), val)
    }
}

impl FromDataItem for f32 {
    fn typ() -> DataType {
        DataType::Double
    }
    unsafe fn from_item_unchecked(item: *mut obs_data_item_t) -> Self {
        obs_data_item_get_double(item) as f32
    }
    unsafe fn set_default_unchecked(obj: *mut obs_data_t, name: ObsString, val: Self) {
        obs_data_set_default_double(obj, name.as_ptr(), val as f64)
    }
}

impl FromDataItem for bool {
    fn typ() -> DataType {
        DataType::Boolean
    }
    unsafe fn from_item_unchecked(item: *mut obs_data_item_t) -> Self {
        obs_data_item_get_bool(item)
    }
    unsafe fn set_default_unchecked(obj: *mut obs_data_t, name: ObsString, val: Self) {
        obs_data_set_default_bool(obj, name.as_ptr(), val)
    }
}

impl FromDataItem for DataObj<'_> {
    fn typ() -> DataType {
        DataType::Object
    }
    unsafe fn from_item_unchecked(item: *mut obs_data_item_t) -> Self {
        Self::from_raw(obs_data_item_get_obj(item))
    }
    unsafe fn set_default_unchecked(obj: *mut obs_data_t, name: ObsString, mut val: Self) {
        obs_data_set_default_obj(obj, name.as_ptr(), val.as_ptr_mut())
    }
}

impl FromDataItem for DataArray<'_> {
    fn typ() -> DataType {
        DataType::Array
    }
    unsafe fn from_item_unchecked(item: *mut obs_data_item_t) -> Self {
        Self::from_raw(obs_data_item_get_array(item))
    }
    unsafe fn set_default_unchecked(_obj: *mut obs_data_t, _name: ObsString, _val: Self) {
        unimplemented!("obs_data_set_default_array function doesn't exist")
    }
}

/// A smart pointer to `obs_data_t`
pub struct DataObj<'parent> {
    raw: *mut obs_data_t,
    _parent: PhantomData<&'parent DataObj<'parent>>,
}

impl PtrWrapper for DataObj<'_> {
    type Pointer = obs_data_t;

    unsafe fn from_raw(raw: *mut Self::Pointer) -> Self {
        Self {
            raw,
            _parent: PhantomData,
        }
    }

    fn as_ptr(&self) -> *const Self::Pointer {
        self.raw
    }
}

impl Default for DataObj<'_> {
    fn default() -> Self {
        DataObj::new()
    }
}

impl DataObj<'_> {
    /// Creates a empty data object
    pub fn new() -> Self {
        unsafe {
            let raw = obs_data_create();
            Self::from_raw(raw)
        }
    }

    /// Loads data into a object from a JSON string.
    pub fn from_json(json_str: impl Into<ObsString>) -> Option<Self> {
        let json_str = json_str.into();
        unsafe {
            let raw = obs_data_create_from_json(json_str.as_ptr());
            if raw.is_null() {
                None
            } else {
                Some(Self::from_raw(raw))
            }
        }
    }

    /// Loads data into a object from a JSON file.
    /// * `backup_ext`: optional backup file path in case the original file is
    ///   bad.
    pub fn from_json_file(
        json_file: impl Into<ObsString>,
        backup_ext: impl Into<Option<ObsString>>,
    ) -> Option<Self> {
        let json_file = json_file.into();

        unsafe {
            let raw = if let Some(backup_ext) = backup_ext.into() {
                obs_data_create_from_json_file_safe(json_file.as_ptr(), backup_ext.as_ptr())
            } else {
                obs_data_create_from_json_file(json_file.as_ptr())
            };
            if raw.is_null() {
                None
            } else {
                Some(Self::from_raw(raw))
            }
        }
    }

    /// Fetches a property from this object. Numbers are implicitly casted.
    pub fn get<T: FromDataItem>(&self, name: impl Into<ObsString>) -> Option<T> {
        let name = name.into();
        let mut item_ptr = unsafe { obs_data_item_byname(self.as_ptr() as *mut _, name.as_ptr()) };
        if item_ptr.is_null() {
            return None;
        }
        // Release it immediately since it is also referenced by this object.
        unsafe {
            obs_data_item_release(&mut item_ptr);
        }
        assert!(!item_ptr.is_null()); // We should not be the last holder

        let typ = unsafe { DataType::from_item(item_ptr) };

        if typ == T::typ() {
            Some(unsafe { T::from_item_unchecked(item_ptr) })
        } else {
            None
        }
    }

    /// Sets a default value for the key.
    ///
    /// Notes
    /// -----
    /// Setting a default value for a [`DataArray`] is not supported and will panic.
    pub fn set_default<T: FromDataItem>(
        &mut self,
        name: impl Into<ObsString>,
        value: impl Into<T>,
    ) {
        unsafe { T::set_default_unchecked(self.as_ptr_mut(), name.into(), value.into()) }
    }

    /// Creates a JSON representation of this object.
    pub fn get_json(&self) -> Option<String> {
        unsafe {
            let ptr = obs_data_get_json(self.raw);
            if ptr.is_null() {
                None
            } else {
                let slice = CStr::from_ptr(ptr);
                Some(slice.to_string_lossy().into_owned())
            }
        }
    }

    /// Clears all values.
    pub fn clear(&mut self) {
        unsafe {
            obs_data_clear(self.raw);
        }
    }

    pub fn remove(&mut self, name: impl Into<ObsString>) {
        let name = name.into();
        unsafe {
            obs_data_erase(self.raw, name.as_ptr());
        }
    }
}

impl Drop for DataObj<'_> {
    fn drop(&mut self) {
        unsafe {
            obs_data_release(self.raw);
        }
    }
}

pub struct DataArray<'parent> {
    raw: *mut obs_data_array_t,
    _parent: PhantomData<&'parent DataArray<'parent>>,
}

impl PtrWrapper for DataArray<'_> {
    type Pointer = obs_data_array_t;

    unsafe fn from_raw(raw: *mut Self::Pointer) -> Self {
        Self {
            raw,
            _parent: PhantomData,
        }
    }

    fn as_ptr(&self) -> *const Self::Pointer {
        self.raw
    }
}

impl DataArray<'_> {
    pub fn len(&self) -> usize {
        unsafe { obs_data_array_count(self.raw) as usize }
    }

    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    pub fn get(&self, index: usize) -> Option<DataObj> {
        let ptr = unsafe { obs_data_array_item(self.raw, index as size_t) };
        if ptr.is_null() {
            None
        } else {
            Some(unsafe { DataObj::from_raw(ptr) })
        }
    }
}

impl Drop for DataArray<'_> {
    fn drop(&mut self) {
        unsafe {
            obs_data_array_release(self.raw);
        }
    }
}