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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
use std::any::{type_name, Any, TypeId};
use std::ffi::c_void;
use std::fmt::{Binary, Debug, Formatter, Octal, UpperHex};
use std::ops::{Deref, DerefMut};
use std::sync::Arc;

use parking_lot::lock_api::{MappedRwLockReadGuard, MappedRwLockWriteGuard, RwLockReadGuard};
use parking_lot::{RawRwLock, RwLock, RwLockWriteGuard};

use crate::{AnyValue, PhlowExtension, PhlowView, PhlowViewMethod, PrintExtensions};

pub type PhlowObjectId = i64;

#[derive(Clone)]
pub struct PhlowObject(Arc<PhlowObjectData>);
struct PhlowObjectData {
    // to make sure that when we browse a reference, it stays alive as long as the previous inspector is alive
    parent: Option<PhlowObject>,
    // when value is reference - the previous inspector must be initialized
    value: RwLock<AnyValue>,
    // meta description of the type with the necessary vtables
    phlow_type: PhlowType,
    generic_types: Vec<PhlowType>,
    #[cfg(feature = "object-id")]
    id: PhlowObjectId,
}

impl PhlowObject {
    pub fn object<T: Any>(
        object: T,
        phlow_extensions_fn: impl Fn(&T) -> Vec<PhlowExtension> + 'static,
    ) -> Self {
        let phlow_type = PhlowType::new::<T>(|| phlow_extensions_fn(&object));
        Self::new(AnyValue::object(object), phlow_type, vec![], None)
    }

    pub fn object_with_generics<T: 'static>(
        object: T,
        phlow_extensions_fn: impl Fn(&T) -> Vec<PhlowExtension> + 'static,
        generic_types: Vec<PhlowType>,
    ) -> Self {
        let phlow_type = PhlowType::new::<T>(|| phlow_extensions_fn(&object));
        Self::new(AnyValue::object(object), phlow_type, generic_types, None)
    }

    pub fn reference<T: 'static>(
        object: &T,
        parent: &PhlowObject,
        phlow_extensions_fn: impl Fn(&T) -> Vec<PhlowExtension> + 'static,
    ) -> Self {
        let phlow_type = PhlowType::new::<T>(|| phlow_extensions_fn(object));
        Self::new(
            AnyValue::reference(object),
            phlow_type,
            vec![],
            Some(parent.clone()),
        )
    }

    pub fn construct_reference<T: 'static>(
        reference: &T,
        phlow_type: PhlowType,
        parent: Option<PhlowObject>,
    ) -> Self {
        Self::new(AnyValue::reference(reference), phlow_type, vec![], parent)
    }

    pub fn new(
        value: AnyValue,
        phlow_type: PhlowType,
        generic_types: Vec<PhlowType>,
        parent: Option<PhlowObject>,
    ) -> Self {
        Self(Arc::new(PhlowObjectData {
            parent,
            value: RwLock::new(value),
            phlow_type,
            generic_types,
            #[cfg(feature = "object-id")]
            id: unique_id::Generator::<i64>::next_id(
                &unique_id::sequence::SequenceGenerator::default(),
            ),
        }))
    }

    pub fn phlow_type(&self) -> &PhlowType {
        &self.0.phlow_type
    }

    pub fn generic_phlow_type(&self, index: usize) -> Option<PhlowType> {
        self.0.generic_types.get(index).cloned()
    }

    pub fn generic_phlow_types(&self) -> &[PhlowType] {
        self.0.generic_types.as_slice()
    }

    pub fn to_string(&self) -> String {
        self.with_value(|value| self.0.phlow_type.value_to_string(value))
    }

    #[cfg(feature = "object-id")]
    pub fn object_id(&self) -> PhlowObjectId {
        self.0.id
    }

    /// Return true if phlow object contains a value - object or reference.
    /// Note, that even though has_value() may return true, it does not mean
    /// that the value can actually be taken, because it does not check
    /// the runtime type.
    pub fn has_value(&self) -> bool {
        self.0.value.read().has_value()
    }

    /// Take the ownership of the value leaving AnyValue::None in its place.
    /// The value can only be taken if phlow object owned it
    pub fn take_value<T: Any>(&self) -> Option<T> {
        let mut writer = self.0.value.write();
        let previous = std::mem::replace(&mut *writer, AnyValue::None);
        previous.take_value()
    }

    /// Replace an existing value with the given object and returns the previous object if any.
    pub fn replace_value<T: Any>(&self, object: T) -> Option<T> {
        let mut writer = self.0.value.write();
        let previous = std::mem::replace(&mut *writer, AnyValue::object(object));
        previous.take_value()
    }

    /// Attempts to clone the value
    pub fn clone_value<T: Any + Clone>(&self) -> Option<T> {
        self.0.value.read().clone_value()
    }

    pub fn with_value<R>(&self, op: impl FnOnce(&AnyValue) -> R) -> R {
        op(&self.0.value.read())
    }

    pub fn value(&self) -> RwLockReadGuard<'_, RawRwLock, AnyValue> {
        self.0.value.read()
    }

    pub fn value_mut<T: Any>(&self) -> Option<MappedRwLockWriteGuard<'_, RawRwLock, T>> {
        RwLockWriteGuard::try_map(self.0.value.write(), |value| value.as_mut_safe())
            .map(|reference| Some(reference))
            .unwrap_or(None)
    }

    pub fn value_ref<T: Any>(&self) -> Option<MappedRwLockReadGuard<'_, RawRwLock, T>> {
        RwLockReadGuard::try_map(self.0.value.read(), |value| value.as_ref_safe())
            .map(|reference| Some(reference))
            .unwrap_or(None)
    }

    pub fn value_ptr(&self) -> *const c_void {
        self.value().as_ptr()
    }

    pub fn value_type_name(&self) -> &str {
        self.0.phlow_type.type_name()
    }

    pub fn parent(&self) -> Option<&PhlowObject> {
        self.0.parent.as_ref()
    }

    pub fn phlow_view_methods(&self) -> Vec<PhlowViewMethod> {
        self.0
            .phlow_type
            .phlow_extensions
            .iter()
            .map(|extension| extension.view_methods())
            .flatten()
            .collect()
    }

    pub fn phlow_view_named(&self, name: impl AsRef<str>) -> Option<Box<dyn PhlowView>> {
        let target_name: &str = name.as_ref();

        self.phlow_view_methods()
            .into_iter()
            .find(|each_method| each_method.method_name.as_str() == target_name)
            .and_then(|each_method| each_method.as_view(&self))
    }

    pub fn phlow_views(&self) -> Vec<Box<dyn PhlowView>> {
        self.phlow_view_methods()
            .into_iter()
            .map(|each_method| each_method.as_view(&self))
            .filter(|each_view| each_view.is_some())
            .map(|each_view| each_view.unwrap())
            .collect()
    }
}

impl Debug for PhlowObject {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.debug_struct(type_name::<Self>())
            .field("extensions", &self.phlow_view_methods())
            .finish()
    }
}

pub trait AsPhlowObject {
    fn is_phlow_object(&self) -> bool;
    fn try_into_phlow_object(&self) -> Option<PhlowObject>;
}

impl<T> AsPhlowObject for T {
    default fn is_phlow_object(&self) -> bool {
        false
    }

    default fn try_into_phlow_object(&self) -> Option<PhlowObject> {
        None
    }
}

impl AsPhlowObject for PhlowObject {
    fn is_phlow_object(&self) -> bool {
        true
    }

    fn try_into_phlow_object(&self) -> Option<PhlowObject> {
        Some(self.clone())
    }
}

impl AsPhlowObject for &PhlowObject {
    fn is_phlow_object(&self) -> bool {
        true
    }

    fn try_into_phlow_object(&self) -> Option<PhlowObject> {
        (*self).try_into_phlow_object()
    }
}

pub struct TypedPhlowObject<'value, T: 'static> {
    object: &'value PhlowObject,
    reference: &'value T,
}

impl<'value, T: 'static> TypedPhlowObject<'value, T> {
    pub fn new(object: &'value PhlowObject, reference: &'value T) -> Self {
        Self { reference, object }
    }

    pub fn phlow_object(&self) -> &PhlowObject {
        &self.object
    }
}

impl<'value, T: 'static> AsRef<T> for TypedPhlowObject<'value, T> {
    fn as_ref(&self) -> &'value T {
        self.reference
    }
}

impl<'value, T: 'static> Deref for TypedPhlowObject<'value, T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        self.reference
    }
}

impl<'value, T: 'static> ToString for TypedPhlowObject<'value, T> {
    fn to_string(&self) -> String {
        self.object.to_string()
    }
}

impl<'value, T: Debug + 'static> Debug for TypedPhlowObject<'value, T> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        Debug::fmt(self.reference, f)
    }
}

impl<'value, T: UpperHex + 'static> UpperHex for TypedPhlowObject<'value, T> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        UpperHex::fmt(self.reference, f)
    }
}

impl<'value, T: Octal + 'static> Octal for TypedPhlowObject<'value, T> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        Octal::fmt(self.reference, f)
    }
}

impl<'value, T: Binary + 'static> Binary for TypedPhlowObject<'value, T> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        Binary::fmt(self.reference, f)
    }
}

pub struct TypedPhlowObjectMut<'value, T: 'static> {
    object: &'value PhlowObject,
    reference: &'value mut T,
}

impl<'value, T: 'static> TypedPhlowObjectMut<'value, T> {
    pub fn new(object: &'value PhlowObject, reference: &'value mut T) -> Self {
        Self { reference, object }
    }

    pub fn phlow_object(&self) -> &PhlowObject {
        &self.object
    }
}

impl<'value, T: 'static> AsRef<T> for TypedPhlowObjectMut<'value, T> {
    fn as_ref(&self) -> &T {
        self.reference
    }
}

impl<'value, T: 'static> AsMut<T> for TypedPhlowObjectMut<'value, T> {
    fn as_mut(&mut self) -> &mut T {
        self.reference
    }
}

impl<'value, T: 'static> Deref for TypedPhlowObjectMut<'value, T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        self.reference
    }
}

impl<'value, T: 'static> DerefMut for TypedPhlowObjectMut<'value, T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.reference
    }
}

impl<'value, T: 'static> ToString for TypedPhlowObjectMut<'value, T> {
    fn to_string(&self) -> String {
        self.object.to_string()
    }
}

impl<'value, T: Debug + 'static> Debug for TypedPhlowObjectMut<'value, T> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        Debug::fmt(self.reference, f)
    }
}

impl<'value, T: UpperHex + 'static> UpperHex for TypedPhlowObjectMut<'value, T> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        UpperHex::fmt(self.reference, f)
    }
}

impl<'value, T: Octal + 'static> Octal for TypedPhlowObjectMut<'value, T> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        Octal::fmt(self.reference, f)
    }
}

impl<'value, T: Binary + 'static> Binary for TypedPhlowObjectMut<'value, T> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        Binary::fmt(self.reference, f)
    }
}

#[derive(Debug, Clone)]
#[repr(C)]
pub struct PhlowType {
    // the full type path as a string
    type_name: &'static str,
    type_id: TypeId,
    // extensions are simple vtable that know functions used to get specific extensions
    phlow_extensions: Vec<PhlowExtension>,
    // detects available printable options such as Display, Debug etc..
    print_extensions: PrintExtensions,
}

impl PhlowType {
    pub fn of<T: 'static>(
        value: &T,
        phlow_extensions_fn: impl Fn(&T) -> Vec<PhlowExtension> + 'static,
    ) -> Self {
        Self::new::<T>(|| phlow_extensions_fn(value))
    }

    pub fn new<T: 'static>(phlow_extensions_fn: impl Fn() -> Vec<PhlowExtension>) -> Self {
        let phlow_extensions = phlow_extensions_fn();
        let print_extensions = PrintExtensions::new::<T>();
        Self {
            type_name: type_name::<T>(),
            type_id: TypeId::of::<T>(),
            phlow_extensions,
            print_extensions,
        }
    }

    pub fn type_name(&self) -> &str {
        self.type_name
    }

    pub fn value_to_string(&self, value: &AnyValue) -> String {
        self.print_extensions.to_string(value)
    }
}