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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
use std::{fmt::Debug, hash::Hash, marker::PhantomData, num::NonZeroU64, ops::Deref};

use legion::{
    storage::{Archetype, Component},
    world::{ComponentError, EntityLocation},
};
use num::ToPrimitive;

use crate::{
    filter::{Bloom, BloomResult, BloomSize, BF},
    hashed::{NodeHashs, SyntaxNodeHashs, SyntaxNodeHashsKinds},
    impact::serialize::{CachedHasher, Keyed, MySerialize},
    nodes::{CompressedNode, HashSize, RefContainer},
    store::defaults::LabelIdentifier,
    types::{
        Children, HyperType, IterableChildren, MySlice, NodeId, TypeTrait, Typed, TypedNodeId,
        WithChildren, WithMetaData,
    },
};

use super::compo::{self, NoSpacesCS, CS};

pub type NodeIdentifier = legion::Entity;
pub type EntryRef<'a> = legion::world::EntryRef<'a>;
#[repr(transparent)]
pub struct HashedNodeRef<'a, T = NodeIdentifier>(pub(super) EntryRef<'a>, PhantomData<T>);

impl<'a, T> HashedNodeRef<'a, T> {
    #[doc(hidden)]
    pub fn cast_type<U: NodeId>(self) -> HashedNodeRef<'a, U>
    where
        T: NodeId<IdN = U::IdN>,
    {
        HashedNodeRef(self.0, PhantomData)
    }
    pub(super) fn new(e: EntryRef<'a>) -> Self {
        Self(e, PhantomData)
    }
}

impl NodeId for NodeIdentifier {
    type IdN = Self;
    fn as_id(&self) -> &Self::IdN {
        self
    }
    unsafe fn from_id(id: Self::IdN) -> Self {
        id
    }

    unsafe fn from_ref_id(id: &Self::IdN) -> &Self {
        id
    }
}

impl TypedNodeId for NodeIdentifier {
    type Ty = crate::types::AnyType;
}

pub struct HashedNode<Id: TypedNodeId<IdN = NodeIdentifier>> {
    node: CompressedNode<NodeIdentifier, LabelIdentifier, Id::Ty>,
    hashs: SyntaxNodeHashs<u32>,
}

// impl<'a> Symbol<HashedNodeRef<'a>> for legion::Entity {}

// * hashed node impl

impl<'a, Id: TypedNodeId<IdN = NodeIdentifier>> PartialEq for HashedNode<Id>
where
    Id::IdN: PartialEq,
{
    fn eq(&self, other: &Self) -> bool {
        self.node == other.node
    }
}

impl<'a, Id: TypedNodeId<IdN = NodeIdentifier>> Eq for HashedNode<Id> where Id::IdN: Eq {}

impl<'a, Id: TypedNodeId<IdN = NodeIdentifier>> Hash for HashedNode<Id> {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.hashs.hash(&Default::default()).hash(state)
    }
}
// impl<'a, Id: TypedNodeId<IdN = NodeIdentifier, Ty=Type>> crate::types::Typed for HashedNode<Id> {
//     type Type = Id::Ty;

//     fn get_type(&self) -> Type {
//         panic!()
//     }
// }

impl<'a, Id: TypedNodeId<IdN = NodeIdentifier>> crate::types::Labeled for HashedNode<Id> {
    type Label = LabelIdentifier;

    fn get_label_unchecked(&self) -> &LabelIdentifier {
        panic!()
    }

    fn try_get_label(&self) -> Option<&Self::Label> {
        todo!()
        // .or_else(|| {
        //     let a = self.0.get_component::<Box<[Space]>>();
        //     let mut b = String::new();
        //     a.iter()
        //         .for_each(|a| Space::fmt(a, &mut b, parent_indent).unwrap());

        // })
    }
}

// impl<'a,T> crate::types::WithChildren for HashedNode<T> {
//     type ChildIdx = u16;

//     fn child_count(&self) -> Self::ChildIdx {
//         todo!()
//     }

//     fn get_child(&self, idx: &Self::ChildIdx) -> Self::TreeId {
//         todo!()
//     }

//     fn get_child_rev(&self, idx: &Self::ChildIdx) -> Self::TreeId {
//         todo!()
//     }

//     fn get_children(&self) -> &[Self::TreeId] {
//         todo!()
//     }

//     fn get_children_cpy(&self) -> Vec<Self::TreeId> {
//         todo!()
//     }

//     fn try_get_children(&self) -> Option<&[Self::TreeId]> {
//         todo!()
//     }
// }

// impl<'a,T> crate::types::Tree for HashedNode<T> {
//     fn has_children(&self) -> bool {
//         todo!()
//     }

//     fn has_label(&self) -> bool {
//         todo!()
//     }
// }

// impl Symbol<HashedNode> for legion::Entity {}

// * hashed node reference impl

impl<'a, Id: TypedNodeId<IdN = NodeIdentifier>> PartialEq for HashedNodeRef<'a, Id> {
    fn eq(&self, other: &Self) -> bool {
        self.0.location().archetype() == other.0.location().archetype()
            && self.0.location().component() == other.0.location().component()
    }
}

impl<'a, Id: TypedNodeId<IdN = NodeIdentifier>> Eq for HashedNodeRef<'a, Id> {}

impl<'a, Id: TypedNodeId<IdN = NodeIdentifier>> Hash for HashedNodeRef<'a, Id> {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        crate::types::WithHashs::hash(self, &Default::default()).hash(state)
    }
}

impl<'a, Id: TypedNodeId<IdN = NodeIdentifier>> Debug for HashedNodeRef<'a, Id> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_tuple("HashedNodeRef")
            .field(&self.0.location())
            .finish()
    }
}

impl<'a, Id> Deref for HashedNodeRef<'a, Id> {
    type Target = EntryRef<'a>;

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

impl<'a, Id: TypedNodeId<IdN = NodeIdentifier>> HashedNodeRef<'a, Id> {
    // TODO when relativisation is applied, caller of this method should provide the size of the paren ident
    pub fn get_bytes_len(&self, _p_indent_len: u32) -> u32
    where
        Id::Ty: 'static + TypeTrait + Send + Sync + Debug,
    {
        // use crate::types::Typed;
        // if self.get_type().is_spaces() {
        //     self.0
        //         .get_component::<compo::BytesLen>()
        //         .expect(&format!(
        //             "node with type {:?} don't have a len",
        //             self.get_type()
        //         ))
        //         .0
        //     // self.get_component::<Box<[Space]>>()
        //     //     .expect("spaces node should have spaces")
        //     //     .iter()
        //     //     .map(|x| {
        //     //         if x == &Space::ParentIndentation {
        //     //             p_indent_len
        //     //         } else {
        //     //             1
        //     //         }
        //     //     })
        //     //     .sum()
        // } else {
        //     self.0
        //         .get_component::<compo::BytesLen>()
        //         .expect(&format!(
        //             "node with type {:?} don't have a len",
        //             self.get_type()
        //         ))
        //         .0
        // }
        // .map_or_else(|_| self
        //     .get_type().to_string().len() as u32,|x|x.0)
        self.0.get_component::<compo::BytesLen>().unwrap().0
    }
}

impl<'a, Id: 'static + TypedNodeId<IdN = NodeIdentifier>> HashedNodeRef<'a, Id> {
    // TODO when relativisation is applied, caller of this method should provide the size of the paren ident
    pub fn try_get_bytes_len(&self, _p_indent_len: u32) -> Option<u32>
    where
        Id::Ty: HyperType + Copy + Send + Sync,
    {
        // use crate::types::Typed;
        if self.get_type().is_spaces() {
            self.0.get_component::<compo::BytesLen>().map(|x| x.0).ok()
            // let s = self.get_component::<Box<[Space]>>().ok()?;
            // let s = s
            //     .iter()
            //     .map(|x| {
            //         if x == &Space::ParentIndentation {
            //             p_indent_len
            //         } else {
            //             1
            //         }
            //     })
            //     .sum();
            // Some(s)
        } else {
            self.0.get_component::<compo::BytesLen>().map(|x| x.0).ok()
        }
        // .map_or_else(|_| self
        //     .get_type().to_string().len() as u32,|x|x.0)
    }

    pub fn is_directory(&self) -> bool
    where
        Id: HyperType + Copy + Send + Sync,
    {
        self.get_type().is_directory()
    }
}

impl<'a, T, C: Component> WithMetaData<C> for HashedNodeRef<'a, T> {
    fn get_metadata(&self) -> Option<&C> {
        self.0.get_component::<C>().ok()
    }
}

impl<'a, T> HashedNodeRef<'a, T> {
    // pub(crate) fn new(entry: EntryRef<'a>) -> Self {
    //     Self(entry)
    // }

    /// Returns the entity's archetype.
    pub fn archetype(&self) -> &Archetype {
        self.0.archetype()
    }

    /// Returns the entity's location.
    pub fn location(&self) -> EntityLocation {
        self.0.location()
    }

    /// Returns a reference to one of the entity's components.
    pub fn into_component<C: Component>(self) -> Result<&'a C, ComponentError> {
        self.0.into_component::<C>()
    }

    /// Returns a mutable reference to one of the entity's components.
    ///
    /// # Safety
    /// This function bypasses static borrow checking. The caller must ensure that the component reference
    /// will not be mutably aliased.
    pub unsafe fn into_component_unchecked<C: Component>(
        self,
    ) -> Result<&'a mut C, ComponentError> {
        self.0.into_component_unchecked::<C>()
    }

    /// Returns a reference to one of the entity's components.
    pub fn get_component<C: Component>(&self) -> Result<&C, ComponentError> {
        self.0.get_component::<C>()
    }

    /// Returns a mutable reference to one of the entity's components.
    ///
    /// # Safety
    /// This function bypasses static borrow checking. The caller must ensure that the component reference
    /// will not be mutably aliased.
    pub unsafe fn get_component_unchecked<C: Component>(&self) -> Result<&mut C, ComponentError> {
        self.0.get_component_unchecked::<C>()
    }

    pub fn get_child_by_name(
        &self,
        name: &<HashedNodeRef<'a, T> as crate::types::Labeled>::Label,
    ) -> Option<<HashedNodeRef<'a, T> as crate::types::Stored>::TreeId> {
        let labels = self
            .0
            .get_component::<CS<<HashedNodeRef<'a, T> as crate::types::Labeled>::Label>>()
            .ok()?;
        let idx = labels.0.iter().position(|x| x == name);
        idx.map(|idx| self.child(&idx.to_u16().unwrap()).unwrap())
    }

    pub fn get_child_idx_by_name(
        &self,
        name: &<HashedNodeRef<'a, T> as crate::types::Labeled>::Label,
    ) -> Option<<HashedNodeRef<'a, T> as crate::types::WithChildren>::ChildIdx> {
        let labels = self
            .0
            .get_component::<CS<<HashedNodeRef<'a, T> as crate::types::Labeled>::Label>>()
            .ok()?;
        labels
            .0
            .iter()
            .position(|x| x == name)
            .map(|x| x.to_u16().unwrap())
    }

    pub fn try_get_children_name(
        &self,
    ) -> Option<&[<HashedNodeRef<'a, T> as crate::types::Labeled>::Label]> {
        self.0
            .get_component::<CS<<HashedNodeRef<'a, T> as crate::types::Labeled>::Label>>()
            .ok()
            .map(|x| &*x.0)
    }
}

impl<'a, Id: TypedNodeId<IdN = NodeIdentifier>> HashedNodeRef<'a, Id>
where
    Id::Ty: 'static + Sync + Send + TypeTrait,
{
    pub fn into_compressed_node(
        &self,
    ) -> Result<CompressedNode<legion::Entity, LabelIdentifier, Id::Ty>, ComponentError> {
        // if let Ok(spaces) = self.0.get_component::<Box<[Space]>>() {
        //     return Ok(CompressedNode::Spaces(spaces.clone()));
        // }
        let kind = self.0.get_component::<Id::Ty>()?;
        if kind.is_spaces() {
            let spaces = self.0.get_component::<LabelIdentifier>().unwrap();
            return Ok(CompressedNode::Spaces(spaces.clone()));
        }
        let a = self.0.get_component::<LabelIdentifier>();
        let label: Option<LabelIdentifier> = a.ok().map(|x| x.clone());
        let children = self.children().map(|x| {
            let it = x.iter_children();
            it.map(|x| x.clone()).collect()
        });
        // .0.get_component::<CS<legion::Entity>>();
        // let children = children.ok().map(|x| x.0.clone());
        Ok(CompressedNode::new(
            *kind,
            label,
            children.unwrap_or_default(),
        ))
    }
}

impl<'a, T> AsRef<HashedNodeRef<'a, T>> for HashedNodeRef<'a, T> {
    fn as_ref(&self) -> &HashedNodeRef<'a, T> {
        self
    }
}

impl<'a, Id: 'static + TypedNodeId<IdN = NodeIdentifier>> crate::types::Typed
    for HashedNodeRef<'a, Id>
{
    type Type = Id::Ty;

    fn get_type(&self) -> Id::Ty
    where
        Id::Ty: Copy + Send + Sync,
    {
        *self.0.get_component::<Id::Ty>().unwrap()
    }
}

impl<'a, T> crate::types::WithStats for HashedNodeRef<'a, T> {
    fn size(&self) -> usize {
        self.0
            .get_component::<compo::Size>()
            .ok()
            .and_then(|x| x.0.to_usize())
            .unwrap_or(1)
    }

    fn height(&self) -> usize {
        self.0
            .get_component::<compo::Height>()
            .ok()
            .and_then(|x| x.0.to_usize())
            .unwrap_or(1)
    }
}

impl<'a, T> HashedNodeRef<'a, T> {
    pub fn size_no_spaces(&self) -> usize {
        self.0
            .get_component::<compo::SizeNoSpaces>()
            .ok()
            .and_then(|x| x.0.to_usize())
            .unwrap_or(1)
    }
}

impl<'a, T> crate::types::WithSerialization for HashedNodeRef<'a, T> {
    fn try_bytes_len(&self) -> Option<usize> {
        self.0
            .get_component::<compo::BytesLen>()
            .ok()
            .map(|x| x.0.to_usize().unwrap())
    }
}

impl<'a, T> crate::types::Labeled for HashedNodeRef<'a, T> {
    type Label = LabelIdentifier;

    fn get_label_unchecked(&self) -> &LabelIdentifier {
        self.0
            .get_component::<LabelIdentifier>()
            .expect("check with self.has_label()")
    }

    fn try_get_label(&self) -> Option<&Self::Label> {
        self.0.get_component::<LabelIdentifier>().ok()
        // .or_else(|| {
        //     let a = self.0.get_component::<Box<[Space]>>();
        //     let mut b = String::new();
        //     a.iter()
        //         .for_each(|a| Space::fmt(a, &mut b, parent_indent).unwrap());

        // })
    }
}

impl<'a, T> crate::types::Node for HashedNodeRef<'a, T> {}

impl<'a, T> crate::types::Stored for HashedNodeRef<'a, T> {
    type TreeId = NodeIdentifier;
}
impl<'a, Id: TypedNodeId<IdN = NodeIdentifier>> crate::types::Node for HashedNode<Id> {}
impl<'a, Id: TypedNodeId<IdN = NodeIdentifier>> crate::types::Stored for HashedNode<Id> {
    type TreeId = NodeIdentifier;
}

impl<'a, T> HashedNodeRef<'a, T> {
    pub fn cs(
        &self,
    ) -> Result<&<Self as crate::types::WithChildren>::Children<'_>, ComponentError> {
        // let scount = self.0.get_component::<CSStaticCount>().ok();
        // if let Some(CSStaticCount(scount)) = scount {
        // if *scount == 1 {
        //     self.0
        //         .get_component::<CS0<legion::Entity, 1>>()
        //         .map(|x| x.into())
        //     } else if *scount == 2 {
        //         self.0
        //             .get_component::<CS0<legion::Entity, 2>>()
        //             .map(|x| x.into())
        //     } else
        // if *scount == 3 {
        //     self.0
        //         .get_component::<CS0<legion::Entity, 3>>()
        //         .map(|x| x.into())
        // } else {
        //     panic!()
        // }
        // } else {
        let r = self
            .0
            .get_component::<CS<legion::Entity>>()
            .map(|x| (*x.0).into());
        r
        // }
    }
    pub fn no_spaces(
        &self,
    ) -> Result<&<Self as crate::types::WithChildren>::Children<'_>, ComponentError> {
        self.0
            .get_component::<NoSpacesCS<legion::Entity>>()
            .map(|x| &*x.0)
            .or_else(|_| self.0.get_component::<CS<legion::Entity>>().map(|x| &*x.0))
            .map(|x| (*x).into())
    }
}

impl<'a, T> crate::types::WithChildren for HashedNodeRef<'a, T> {
    type ChildIdx = u16;
    type Children<'b> = MySlice<Self::TreeId> where Self: 'b;

    fn child_count(&self) -> u16 {
        self.cs()
            .map_or(0, |x| {
                let c: u16 = x.child_count();
                c
            })
            .to_u16()
            .expect("too much children")
    }

    fn child(&self, idx: &Self::ChildIdx) -> Option<Self::TreeId> {
        self.cs()
            .unwrap_or_else(|x| {
                log::error!("backtrace: {}", std::backtrace::Backtrace::force_capture());
                panic!("{}", x)
            })
            .0
            .get(idx.to_usize().unwrap())
            .map(|x| *x)
        // .unwrap_or_else(|| {
        //     log::error!("backtrace: {}", std::backtrace::Backtrace::force_capture());
        //     panic!()
        // })
    }

    fn child_rev(&self, idx: &Self::ChildIdx) -> Option<Self::TreeId> {
        let v = self.cs().ok()?;
        // .unwrap_or_else(|x| {
        //     log::error!("backtrace: {}", std::backtrace::Backtrace::force_capture());
        //     panic!("{}", x)
        // });
        // v.0.get(v.len() - 1 - num::cast::<_, usize>(*idx).unwrap()).cloned()
        let c: Self::ChildIdx = v.child_count();
        let c = c.checked_sub(idx.checked_add(1)?)?;
        v.get(c).cloned()
    }

    // unsafe fn children_unchecked<'b>(&'b self) -> &'b [Self::TreeId] {
    //     let cs = self.cs().unwrap_or_else(|x| {
    //         log::error!("backtrace: {}", std::backtrace::Backtrace::force_capture());
    //         panic!("{}", x)
    //     });
    //     cs
    // }

    // fn get_children_cpy<'b>(&'b self) -> Vec<Self::TreeId> {
    //     let cs = self.cs().unwrap_or_else(|x| {
    //         log::error!("backtrace: {}", std::backtrace::Backtrace::force_capture());
    //         panic!("{}", x)
    //     });
    //     cs.to_vec()
    // }

    fn children(&self) -> Option<&Self::Children<'_>> {
        self.cs().ok()
    }
}

impl<'a, T> crate::types::WithHashs for HashedNodeRef<'a, T> {
    type HK = SyntaxNodeHashsKinds;
    type HP = HashSize;

    fn hash(&self, kind: &Self::HK) -> Self::HP {
        self.0
            .get_component::<SyntaxNodeHashs<Self::HP>>()
            .unwrap()
            .hash(kind)
    }
}

impl<'a, Id: 'static + TypedNodeId<IdN = NodeIdentifier>> crate::types::Tree
    for HashedNodeRef<'a, Id>
{
    fn has_children(&self) -> bool {
        self.cs().map(|x| !x.is_empty()).unwrap_or(false)
    }

    fn has_label(&self) -> bool {
        self.0.get_component::<LabelIdentifier>().is_ok()
    }
}

impl<'a, T> HashedNodeRef<'a, T> {}

impl<'a, T> RefContainer for HashedNodeRef<'a, T> {
    type Result = BloomResult;

    fn check<U: MySerialize + Keyed<usize>>(&self, rf: U) -> Self::Result {
        use crate::filter::BF as _;

        let Ok(e) = self.0.get_component::<BloomSize>() else {
            return BloomResult::MaybeContain
        };
        macro_rules! check {
        ( $($t:ty),* ) => {
            match *e {
                BloomSize::Much => {
                    log::trace!("[Too Much]");
                    BloomResult::MaybeContain
                },
                BloomSize::None => BloomResult::DoNotContain,
                $( <$t>::SIZE => {
                    let x = CachedHasher::<usize,<$t as BF<[u8]>>::S, <$t as BF<[u8]>>::H>::once(rf);
                    let x = x.into_iter().map(|x|<$t>::check_raw(self.0.get_component::<$t>().unwrap(), x));

                    for x in x {
                        if let BloomResult::MaybeContain = x {
                            return BloomResult::MaybeContain
                        }
                    }
                    BloomResult::DoNotContain
                }),*
            }
        };
    }
        check![
            Bloom<&'static [u8], u16>,
            Bloom<&'static [u8], u32>,
            Bloom<&'static [u8], u64>,
            Bloom<&'static [u8], [u64; 2]>,
            Bloom<&'static [u8], [u64; 4]>,
            Bloom<&'static [u8], [u64; 8]>,
            Bloom<&'static [u8], [u64; 16]>,
            Bloom<&'static [u8], [u64; 32]>,
            Bloom<&'static [u8], [u64; 64]>
        ]
    }
}