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
// reference.rs

use crate::{
    attribute::AttributeValue,
    parse::Parse,

    prolog::subset::entity::{entity_value::EntityValue, EntitySource},
    //transcode::{decode_digit, decode_hex},
    transcode::Decode,
    IResult,
    Name,
};
use nom::{
    branch::alt,
    bytes::complete::tag,
    character::complete::{char, digit1, hex_digit1},
    combinator::map,
    sequence::tuple,
};
use std::{cell::RefCell, collections::HashMap, rc::Rc};

#[derive(Clone, PartialEq, Eq)]
pub enum Reference {
    EntityRef(Name),
    CharRef(String),
}

impl<'a> Parse<'a> for Reference {
    type Args = EntitySource;
    //);
    type Output = IResult<&'a str, Self>;
    //[67] Reference ::= EntityRef | CharRef
    fn parse(input: &'a str, args: Self::Args) -> Self::Output {
        alt((
            move |i| Self::parse_entity_ref(i, args.clone()),
            Self::parse_char_reference,
        ))(input)
    }
}
impl Reference {
    pub(crate) fn normalize_entity(
        &self,
        entity_references: Rc<RefCell<HashMap<(Name, EntitySource), EntityValue>>>,
    ) -> EntityValue {
        match self {
            Reference::EntityRef(name) => {
                let refs_map = entity_references.borrow();

                // Try to find the most appropriate source based on available references
                let possible_sources = [EntitySource::External, EntitySource::Internal];
                let entity_value = possible_sources
                    .iter()
                    .filter_map(|source| refs_map.get(&(name.clone(), source.clone())).cloned())
                    .next()
                    .unwrap_or_else(|| EntityValue::Value(name.local_part.clone())); // Default to just returning the name if no entity is found

                match entity_value {
                    EntityValue::Value(val) => {
                        if refs_map.contains_key(&(
                            Name {
                                prefix: None,
                                local_part: val.clone(),
                            },
                            EntitySource::Internal,
                        )) {
                            // This value is another reference, recurse
                            let reference_name = Name {
                                prefix: None,
                                local_part: val,
                            };
                            Reference::EntityRef(reference_name)
                                .normalize_entity(entity_references.clone())
                        } else {
                            EntityValue::Value(val)
                        }
                    }
                    EntityValue::Reference(ref next_ref) => {
                        // Recursively resolve the next reference
                        next_ref.normalize_entity(entity_references.clone())
                    }
                    _ => entity_value,
                }
            }
            Reference::CharRef(value) => EntityValue::Value(value.clone()),
        }
    }

    pub(crate) fn normalize_attribute(
        &self,
        entity_references: Rc<RefCell<HashMap<(Name, EntitySource), EntityValue>>>,
        entity_source: EntitySource,
    ) -> AttributeValue {
        match self {
            Reference::EntityRef(name) => {
                let refs_map = entity_references.borrow();
                match refs_map
                    .get(&(name.clone(), entity_source.clone()))
                    .cloned()
                {
                    Some(EntityValue::Value(val))
                        if refs_map.contains_key(&(
                            Name {
                                prefix: None,
                                local_part: val.clone(),
                            },
                            entity_source.clone(),
                        )) =>
                    {
                        let reference_name = Name {
                            prefix: None,
                            local_part: val,
                        };
                        Reference::EntityRef(reference_name)
                            .normalize_attribute(entity_references.clone(), entity_source.clone())
                    }
                    Some(EntityValue::Reference(Reference::EntityRef(entity))) => {
                        if let Some(EntityValue::Value(val)) = refs_map
                            .get(&(entity.clone(), EntitySource::Internal))
                            .cloned()
                        {
                            AttributeValue::Value(val)
                        } else {
                            Reference::EntityRef(entity.clone()).normalize_attribute(
                                entity_references.clone(),
                                EntitySource::External, //TODO COME BACK TO THIS
                            )
                        }
                    }
                    Some(entity_value) => {
                        // Convert EntityValue to AttributeValue
                        match entity_value {
                            EntityValue::Value(val) => AttributeValue::Value(val),
                            EntityValue::Reference(reference) => reference.normalize_attribute(
                                entity_references.clone(),
                                entity_source.clone(),
                            ),
                            _ => panic!("Unexpected EntityValue variant"),
                        }
                    }
                    None => AttributeValue::Value(name.local_part.clone()),
                }
            }
            Reference::CharRef(value) => AttributeValue::Value(value.clone()),
        }
    }
}

impl<'a> ParseReference<'a> for Reference {}
impl Decode for Reference {
    fn as_str(&self) -> &str {
        match self {
            Reference::EntityRef(name) => &name.local_part,
            Reference::CharRef(value) => value,
        }
    }
}

pub trait ParseReference<'a>: Parse<'a> + Decode {
    //[68] EntityRef ::= '&' Name ';'
    fn parse_entity_ref(input: &str, _entity_source: EntitySource) -> IResult<&str, Reference> {
        let (input, reference) = map(
            tuple((char('&'), Self::parse_name, char(';'))),
            |(_, name, _)| Reference::EntityRef(name),
        )(input)?;
        Ok((input, reference))
    }

    //[69] PEReference ::= '%' Name ';'
    fn parse_parameter_reference(input: &str) -> IResult<&str, Reference> {
        let (input, output) = map(
            tuple((char('%'), Self::parse_name, char(';'))),
            |(_, name, _)| Reference::EntityRef(name),
        )(input)?;
        Ok((input, output))
    }

    //[66] CharRef ::= '&#' [0-9]+ ';' | '&#x' [0-9a-fA-F]+ ';'
    fn parse_char_reference(input: &str) -> IResult<&str, Reference> {
        //TODO: remove reconstruction if possible
        alt((
            map(
                tuple((tag("&#"), digit1, tag(";"))),
                |(start, digits, end): (&str, &str, &str)| {
                    let reconstructed = format!("{}{}{}", start, digits, end);
                    let decoded = reconstructed.decode().unwrap().into_owned();
                    Reference::CharRef(decoded)
                },
            ),
            map(
                tuple((tag("&#x"), hex_digit1, tag(";"))),
                |(start, hex, end): (&str, &str, &str)| {
                    let reconstructed = format!("{}{}{}", start, hex, end);
                    let decoded = reconstructed.decode().unwrap().into_owned();
                    Reference::CharRef(decoded)
                },
            ),
        ))(input)
    }
}